Search code examples
javajavacbytecodecompiler-optimization

Why is Java compiler not optimizing a trivial method?


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)

Solution

  • A typical Java virtual machine optimizes your program at runtime, not during compilation. At runtime, the JVM knows a lot more about your application, both about the actual behavior of your program and about the actual hardware your program is executed upon.

    The byte code is merely a description of how your program is supposed to behave. The runtime is free to apply any optimization to your byte code.

    Of course, one can argue that such trivial optimizations could be applied even during compilation but in general it makes sense to not distribute optimizations over several steps. Any optimization is effectively causing a loos of information about the original program and this might make other optimizations impossible. This said, not all "best optimizations" are always obvious. An easy approach to this is to simply drop (almost) all optimizations during compilation and to apply them at runtime instead.