Will the Java compiler precalculate sums of literals?

你。 提交于 2019-12-23 16:18:26

问题


int i = 10 + 20;

Is it true that the compiler will process this code, adding 10 + 20, and the byte code is the same as for this line of code?

int i = 30;

Where can I read about it?


回答1:


Yes, and you can even verify it for yourself. Take a small Java file, for example:

public class Main {
  public Main() {
    int i = 10 + 20;
  }
}

Compile it with javac Main.java, and then run javap -c Main to disassemble it:

Compiled from "Main.java"
public class Main extends java.lang.Object{
public Main();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   bipush  30
   6:   istore_1
   7:   return

}

Clearly in the bytecode, you can see the compiler's optimization: bipush 30!




回答2:


Yes. This compiler optimization is called constant folding. There's another compiler optimization called sparse conditional constant propagation that does something similar.

In general, there's no guarantee that a given compiler will actually fold constants, but nowadays just about every compiler for every language does this. In particular, the Java Language Specification requires that constant expressions be evaluated at compile time.




回答3:


Yes, it will be simplified as required by the JLS (thanks to @EJP for this precision).

If you want more resources and javac optimization you should take a look at Compiler optimizations or Java Compilers.

Another interesting thing is that even if your code is optimized during the compilation, a second optimization will be done during runtime with hotspot.


Resources :

  • Compiler optimizations
  • Java Compilers

On the same topic :

  • java compiler optimization
  • How to see JIT-compiled code in JVM?


来源:https://stackoverflow.com/questions/3898259/will-the-java-compiler-precalculate-sums-of-literals

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