Final关键字之于Java性能的影响

背景

在阅读OpenTSDB的源码的过程中,注意到其作者几乎在所有能够使用final关键字的地方都使用了。这一点引起我的好奇,因为在我所学习Java的这四年中,我极少使用final 。由于OpenTSDB的作者有着很深的C的渊源,所以想明白其之所以这么做,是出于C/C++带来的习惯,还是对于Java而言,这一声明对于一个数据库系统是极为重要的性能举措之一。

结论

final关键字对于性能的提升是极为有限的,无需关心其在性能方面的影响

以下内容摘自StackOverflow,解释了一些具体内容

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.

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

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.)

EDIT: 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...

Compile-time benefits aside, I could not find any evidence that the use of the keyword final has any measurable effect on performance.

参考

  • https://stackoverflow.com/questions/4279420/does-use-of-final-keyword-in-java-improve-the-performance

你可能感兴趣的:(Final关键字之于Java性能的影响)