Java编译器会预先计算文字和吗? [英] Will the Java compiler precalculate sums of literals?
本文介绍了Java编译器会预先计算文字和吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int i = 10 + 20;
编译器将添加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;
我在哪里可以读到它?
推荐答案
是的,您甚至可以自己进行验证.以一个小的Java文件为例:
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;
}
}
使用javac Main.java
进行编译,然后运行javap -c Main
进行反汇编:
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
}
很明显,在字节码中,您可以看到编译器的优化:bipush 30
!
Clearly in the bytecode, you can see the compiler's optimization: bipush 30
!
这篇关于Java编译器会预先计算文字和吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文