java编译器可以优化此代码吗?

时间:2014-10-23 23:52:57

标签: java optimization dead-code unreachable-code

java编译器或运行时(或任何其他语言编译器)是否足够智能以实现分支3永远不会发生并优化它?我已经看过这种"防御性节目"与许多初学者一起,并想知道这个死重是否保留在字节码中。

import java.util.Random;


class Example
{
    public static void main(String[] args) {
        int x = new Random().nextInt() % 10;
        if ( x < 5 )
        {
            System.out.println("Case 1");
        }
        else
            if ( x >= 5 )
            {
                System.out.println("Case 2");
            }
            else
            {
                System.out.println("Case 3");
            }

    }
}

甚至这个更直率的案例

boolean bool = new Random().nextBoolean();
if ( bool )
{
    System.out.println("Case 1");
}
else
    if ( bool )
    {
        System.out.println("Case 2");
    }

1 个答案:

答案 0 :(得分:4)

我所拥有的Java 8编译器似乎并没有优化它。使用&#34; javap -c&#34;在编译后检查字节代码:

  public static void main(java.lang.String[]);
    Code:
       0: new           #2                  // class java/util/Random
       3: dup
       4: invokespecial #3                  // Method java/util/Random."<init>":()V
       7: invokevirtual #4                  // Method java/util/Random.nextInt:()I
      10: bipush        10
      12: irem
      13: istore_1
      14: iload_1
      15: iconst_5
      16: if_icmpge     30
      19: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
      22: ldc           #6                  // String Case 1
      24: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      27: goto          54
      30: iload_1
      31: iconst_5
      32: if_icmplt     46
      35: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
      38: ldc           #8                  // String Case 2
      40: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      43: goto          54
      46: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
      49: ldc           #9                  // String Case 3
      51: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      54: return
}

字符串&#34;案例3&#34;仍然存在于字节码中。