且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中使用final关键字可以提高性能吗?

更新时间:2023-11-10 11:47:40

通常不是。对于虚方法,HotSpot会跟踪该方法是否已实际被覆盖,并且能够执行优化,例如在假设上内联尚未覆盖方法 - 直到它加载一个覆盖该方法的类,此时它可以撤消(或部分撤消)这些优化。

Usually not. For virtual methods, HotSpot keeps track of whether the method has actually been overridden, and is able to perform optimizations such as inlining on the assumption that a method hasn't been overridden - until it loads a class which overrides the method, at which point it can undo (or partially undo) those optimizations.

(当然,这假设你是使用HotSpot - 但它是迄今为止最常见的JVM,所以...)

(Of course, this is assuming you're using HotSpot - but it's by far the most common JVM, so...)

我想你应该使用 final 基于清晰的设计和可读性而不是出于性能原因。如果您出于性能原因想要更改任何内容,则应在将最清晰的代码变形之前执行适当的测量 - 这样您就可以决定是否所获得的额外性能值得更差的可读性/设计。 (根据我的经验,它几乎永远不值得; YMMV。)

To my mind you should use final based on clear design and readability rather than for performance reasons. If you want to change anything for performance reasons, you should perform appropriate measurements before bending the clearest code out of shape - that way you can decide whether any extra performance achieved is worth the poorer readability/design. (In my experience it's almost never worth it; YMMV.)

编辑:由于已经提到了最后的字段,所以值得提出的是,无论如何它们通常都是个好主意,在清晰的设计方面。它们还在跨线程可见性方面改变了保证行为:在构造函数完成之后,任何最终字段都保证在其他线程中立即可见。根据我的经验,这可能是 final 最常见的用法,虽然作为Josh Bloch的继承设计或禁止它的设计的支持者,我应该使用 final 更常用于课程......

As final fields have been mentioned, it's worth bringing up that they are often a good idea anyway, in terms of clear design. They also change the guaranteed behaviour in terms of cross-thread visibility: after a constructor has completed, any final fields are guaranteed to be visible in other threads immediately. This is probably the most common use of final in my experience, although as a supporter of Josh Bloch's "design for inheritance or prohibit it" rule of thumb, I should probably use final more often for classes...