I've got a simple class for the illustration purposes:
public class Test {
public int test1() {
int result = 100;
result = 200;
return result;
}
public int test2() {
return 200;
}
}
The bytecode produced by the compiler (inspected by javap -c Test.class
) is the following:
public int test1();
Code:
0: bipush 100
2: istore_1
3: sipush 200
6: istore_1
7: iload_1
8: ireturn
public int test2();
Code:
0: sipush 200
3: ireturn
Why is the compiler not optimizing the test1
method to the same bytecode produced for the test2
method? I would expect it to at least avoid redundant initialization of the result
variable considering that it is easy to conclude that the value 100
is not used at all.
I observed this with both Eclipse compiler and javac
.
javac
version: 1.8.0_72
, installed as part of JDK together with Java:
Java(TM) SE Runtime Environment (build 1.8.0_72-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode)