Java常量表达式相关的编译优化代码
16lz
2021-01-22
Here is a simple question about Java compile optimisation.
这是一个关于Java编译优化的简单问题。
Is
final int CONSTANT_NUMBER="Foo Bar".length();
equal to
final int CONSTANT_NUMBER=7;
on compiling code or generally in performance aspect?
编译代码或一般性能方面?
2 个解决方案
#1
2
No the java compiler doesn't evaluate "Foo Bar".length()
at compile time.
没有java编译器在编译时不评估“Foo Bar”.length()。
Consider these classes
考虑这些课程
public class ConstantCheck {
final int CONSTANT_NUMBER = "Foo Bar".length();
}
and
public class ConstantCheck {
final int CONSTANT_NUMBER = 7;
}
Using javap -v
on the compiled .class
file you can see, that the .length()
call is kept:
在已编译的.class文件上使用javap -v可以看到,保留了.length()调用:
The former results in
前者导致
...
final int CONSTANT_NUMBER;
descriptor: I
flags: ACC_FINAL
public text.ConstantCheck();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: ldc #2 // String Foo Bar
7: invokevirtual #3 // Method java/lang/String.length:()I
10: putfield #4 // Field CONSTANT_NUMBER:I
13: return
...
the latter in
后者
...
final int CONSTANT_NUMBER;
descriptor: I
flags: ACC_FINAL
ConstantValue: int 7
public text.ConstantCheck();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 7
7: putfield #2 // Field CONSTANT_NUMBER:I
10: return
....
In the first case the .length
call is present
在第一种情况下,存在.length调用
7: invokevirtual #3 // Method java/lang/String.length:()I
in the second case it's just a constant that is written to the field
在第二种情况下,它只是写入字段的常量
5: bipush 7
7: putfield #2 // Field CONSTANT_NUMBER:I