Why javac does not optimize even simple code?

核能气质少年 提交于 2019-12-19 16:50:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13611829/why-javac-does-not-optimize-even-simple-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!