Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why javac does not optimize even simple code?

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?

like image 434
Marcin Avatar asked Nov 28 '12 18:11

Marcin


People also ask

Does Java compiler optimize code?

More importantly, the javac compiler does not perform simple optimizations like loop unrolling, algebraic simplification, strength reduction, and others. To get these benefits and other simple optimizations, the programmer must perform them on the Java source code and not rely on the javac compiler to perform them.

Which compiler is used by JVM to improve the performance?

The JIT compiler helps improve the performance of Java programs by compiling bytecodes into native machine code at run time. The JIT compiler is enabled by default. When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it.


2 Answers

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.

like image 163
Jon Skeet Avatar answered Oct 20 '22 01:10

Jon Skeet


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.

like image 6
irreputable Avatar answered Oct 20 '22 01:10

irreputable