美文网首页
Final关键字之于Java性能的影响

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

作者: 即墨灯火 | 来源:发表于2018-03-07 16:35 被阅读17次

背景

在阅读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.

参考

相关文章

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

    背景 在阅读OpenTSDB的源码的过程中,注意到其作者几乎在所有能够使用final关键字的地方都使用了。这一点引...

  • Java/转载

    final关键字的性能影响 Java对象内存结构 全面理解Java内存模型 从Java视角理解CPU缓存和伪共享

  • final变量的作用

    参考原文 final这个关键字的作用 final关键字提高了性能。JVM和java应用都会缓存final变量 fi...

  • java - final 关键字

    java - final 关键字 java - final 关键字 在 java 中,final 关键字可以修饰类...

  • Java关键字final、static使用总结

    Java关键字final、static使用总结 一、final 根据程序上下文环境,Java关键字final有“这...

  • Java关键字final、static使用总结

    Java关键字final、static使用总结 一、final 根据程序上下文环境,Java关键字final有“这...

  • 2018-11-14号相关学习资料

    java中final关键字的作用深入理解Java中的final关键字java中的final如何使用和理解PPT和1...

  • final、abstract以及接口

    final关键字 final 关键字可以用来修饰类,属性和方法。 final修饰类 Java 中 final 修饰...

  • 面向对象

    一、类和对象 二、封装 三、继承 Java中final关键字的使用 final关键字: 使用final关键字做标识...

  • Java学习16:final关键字、抽象类和接口

    final关键字 final是java语言中的一个关键字。 final表示最终的,不可变的。 final可以修饰变...

网友评论

      本文标题:Final关键字之于Java性能的影响

      本文链接:https://www.haomeiwen.com/subject/avojfftx.html