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

更多相关文章

  1. 如何在java中获得一个常量?
  2. 《深入理解Java虚拟机》:HotSpot虚拟机内的即时编译器
  3. 【Effective Java】条30:使用枚举代替int常量

随机推荐

  1. android版本更新代码
  2. android java获取当前时间的总结
  3. Android process
  4. Android(安卓)6编译环境搭建 (Marshmallow
  5. android 网络视频代码
  6. Android如何使用XML创建一个环形渐变颜色
  7. android重写Dialog(接上文)
  8. android 自定义线程池ThreadPoolUtils工
  9. Android(Java):自定义控件
  10. android:persistentDrawingCache 的含义