8

Given the following code:

public class MainClass {
    public static int f(){
        int i=0;
        i++;
        return i;
    }
}

the compiler javac produces the following code:

Compiled from "MainClass.java"
public class latte_jvm.MainClass {

  public static int f();
    Code:
       0: iconst_0
       1: istore_0
       2: iinc          0, 1
       5: iload_0
       6: ireturn
}

Function f does really simple thing - it just returns 1. It's so directly translated that it makes me hard to believe that java compiler does any optimizations at all. Why java compiler creators decided to not do such optimizations in the compilation phase?

Marcin
  • 145
  • 5

2 Answers2

17

Is so directly translated that it makes me hard to believe that java compiler does any optimizations at all.

Indeed. Most Java optimization is performed at JIT-time instead. The Java maintainers found out quite a while ago that in many cases, optimizations performed at compile-time actually hindered more important optimizations at JIT-time.

For a few years now, the -O command-line argument has done nothing - and very deliberately so.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But still, couldn't it just do `iconst_1; ireturn`? – Marcin Nov 28 '12 at 18:26
  • 2
    @Marcin It could, but that would take effort, and the JIT already does it. –  Nov 28 '12 at 18:28
  • 2
    +1 IMHO, the few optimisation the `javac` does can be as much a curse as a blessing. e.g. inlining compile time constants. – Peter Lawrey Nov 28 '12 at 18:29
  • Last time I had reason to consider HotSpot, it only JIT'd frequently used methods - it occurs to me then that those whose bytecode is exec'd right on the VM wouldn't be optimised much/any? – jstephenson Nov 28 '12 at 18:37
  • 2
    @jstephenson: Hotspot optimizes progressively - it may choose not to JIT at all the first time it executes a method (which is appropriate for startup code which will be only executed once), but then it will apply progressively "harder" optimizations as it goes. It can also make assumptions, e.g. "no-one's ever going to override this method, so it can be inlined" and then *unoptimize* if those assumptions later on if necessary. Wonderful and frankly terrifying. – Jon Skeet Nov 28 '12 at 18:38
6

Also, by moving optimization to JVM, all JVM based languages can benefit. Compilers (not just javac) have a relatively easier job; language inventors don't have to be optimization experts.

irreputable
  • 44,725
  • 9
  • 65
  • 93