Search code examples
javacompilationjavac

Compiling loops in Java


As I can see from JVM specification this code:

void spin() {
    int i;
    for (i = 0; i < 100; i++) {
        ;    // Loop body is empty
    }
}

should be compiled into:

0   iconst_0
1   istore_1
2   goto 8
5   iinc 1 1
8   iload_1
9   bipush 100
11  if_icmplt 5
14  return  

where condition check if_icmplt is after the loop body, but when I compile it myself and view with javap, I see:

0:   iconst_0
1:   istore_1
2:   iload_1
3:   bipush  100
5:   if_icmpge       14
8:   iinc    1, 1
11:  goto    2
14:  return

and loop condition is before the cycle body. Why does this happen?

Placing condition after body prevents us from doing goto after every cycle and looks logical to me. So why is OracleJDK doing another way?


Solution

  • It is not for better JIT optimizations - for JIT, these code snippets are equivalent. It is because there is no sense to make optimizations in javac, since JIT optimizations are more powerful anyway.