关键字 final 对 JVM 有什么影响吗?

Does the keyword final have any impact on the JVM?

现在,我最近 运行 提出建议,您应该尽可能广泛地使用关键字 final。这很好,以防止程序员开枪打自己的腿——即重新分配不应该重新分配的变量。

但是,它还有其他目的吗?也就是说,JVM 能否使用有关最终变量的信息以某种方式优化字节码,以便它 运行 更快(构建更好的流水线或在多线程环境中使用它)?或者只是一种语法糖,可以最大限度地减少代码开发过程中出错的可能性?

就变量而言,Java 足够聪明,可以判断变量在方法中的任何地方都没有被更改,并将此知识用于优化目的。它不需要您标记变量 final 即可知道。

方法略有不同:当您标记方法 final 时,Java 可以更快地调用此类方法,因为它不再需要检查其覆盖。不过,hotspot 足够聪明,可以判断出没有覆盖,无论是否使用 final.

不过,一般来说,此建议旨在使您的代码更容易被其他人阅读和理解:将变量设为 final 会告诉读者您正在制作常量;做一个 class final 告诉你的读者 class 不是为继承而设计的;使方法成为 final 告诉您的读者,该方法的逻辑应该在整个继承层次结构中保持不变。在长 运行 中,此信息比优化您的 运行ning 代码的潜力更有价值。

final 方法可能会或可能不会被 JVM 内联,直到它们被 JVM 加载之后。因此,如果您确定该方法不会被重新定义,请将其标记为最终方法。

常量应该始终是 static final,因为它们是不可变的,jvm 不需要跟踪这些变量,因为它们永远不会改变。

我觉得这个建议有点太不具体了。

例如;我建议避免在默认情况下在 类 和方法上使用 final(因为 final 类 中断单元测试,分别强制您使用特定的单元测试框架来克服 final methods/classes)。

我还发现对方法参数使用 final 只是浪费了 "screen space"(因此:在 reader 的一侧浪费了 "energy")。

另一方面,只有 类 的最终属性可以 将此类 类 的对象变成不可变的东西;这是一件好事。

如你所见;使用 final 有很多优点和缺点;我认为 "readability" 最常胜过 "potential" 性能改进。

IBM states:

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.