<分区>
现在,我最近遇到了一条建议,建议您应尽可能广泛地使用关键字 final。这很好,可以防止程序员开枪打自己的腿——也就是说,重新分配不应重新分配的变量。
但是,它还有其他目的吗?也就是说,JVM 能否使用有关最终变量的信息以某种方式优化字节码,使其运行得更快(构建更好的流水线或在多线程环境中使用它)?或者只是一种语法糖,可以最大限度地减少代码开发过程中出错的可能性?
<分区>
现在,我最近遇到了一条建议,建议您应尽可能广泛地使用关键字 final。这很好,可以防止程序员开枪打自己的腿——也就是说,重新分配不应重新分配的变量。
但是,它还有其他目的吗?也就是说,JVM 能否使用有关最终变量的信息以某种方式优化字节码,使其运行得更快(构建更好的流水线或在多线程环境中使用它)?或者只是一种语法糖,可以最大限度地减少代码开发过程中出错的可能性?
最佳答案
Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.
关于java - 关键字 final 对 JVM 有什么影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506350/