字节码中丢失了变量"final"修饰符? [英] Variable 'final' modifier lost in Bytecode?

查看:112
本文介绍了字节码中丢失了变量"final"修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分析这个简单类的字节码,我得出的结论是,编译器不保留有关局部变量final的任何信息.不过,这似乎很奇怪,因为我相信HotSpot编译器实际上可以使用此信息进行优化.

Analyzing the bytecode of this simple class, I have come to the conclusion that the compiler doesn't retain any information about a local variable being final. This seems weird though, since I believe the HotSpot compiler could actually use this information to do optimizations.

代码 :

Code:

public static void main(String[] args)
{
    final int i = 10;
    System.out.println(i);
}

字节码 :

Bytecode:

public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
  stack=2, locals=2, args_size=1
     0: bipush        10
     2: istore_1      
     3: getstatic     #16                 // Field java/lang/System.out:Ljava/io/PrintStream;
     6: bipush        10
     8: invokevirtual #22                 // Method java/io/PrintStream.println:(I)V
    11: return        
  LineNumberTable:
    line 7: 0
    line 8: 3
    line 9: 11
  LocalVariableTable:
    Start  Length  Slot  Name   Signature
        0      12     0  args   [Ljava/lang/String;
        3       9     1     i   I

除了节省磁盘空间外,是否有任何特定原因 not 保留本地变量的访问标志?因为对我来说,final似乎是变量的相对平凡的属性.

Is there any specific reason not to retain the access flags of a local variable, other than saving disk space? Because to me, it seems that being final is a relatively non-trivial property of a variable.

推荐答案

final修饰符不存在于字节码中,但是编译器已经使用此信息进行了一些优化.尽管您的示例没有显示它,但是编译器可以在方法的字节码表示形式中内联final变量的值,从而获得更好的性能.如下所示可以显示出差异:

The final modifier is not present in the bytecode but the compiler already uses this information to make some optimization. Although your example doesn't show it, the compiler may inline the final variable's value in the bytecode representation of the method, leading to a better performance. Something like the below can show the difference:

public int addFinal() {
    final int i = 10;
    final int j = 10;
    return i + j;
}

public int addNonFinal() {
    int i = 10;
    int j = 10;
    return i + j;
}

分别为每种方法生成的字节码:

The generated bytecode are respectively for each method:

// addFinal
bipush 10
istore_1
bipush 10
istore_2
bipush 20
ireturn


// addNonFinal
bipush 10
istore_1
bipush 10
istore_2
iload_1
iload_2
iadd
ireturn

这篇关于字节码中丢失了变量"final"修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆