加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java优化:( Hotspot / Dalvik)优化最终方法返回常量?

发布时间:2020-12-14 05:45:49 所属栏目:Java 来源:网络整理
导读:任何人都可以告诉我,Hotspot或Dalvik是否足够聪明,可以内联调用返回常量(静态最终)int值的final方法?理想情况下,方法调用将被常量替换.这可能是在类加载时或通过JIT. 这对我正在研究的一些代码的设计有影响. 解决方法 我认为答案是“不,因为缺少或存在最终
任何人都可以告诉我,Hotspot或Dalvik是否足够聪明,可以内联调用返回常量(静态最终)int值的final方法?理想情况下,方法调用将被常量替换.这可能是在类加载时或通过JIT.

这对我正在研究的一些代码的设计有影响.

解决方法

我认为答案是“不,因为缺少或存在最终关键字而不会发生优化”,至少在HotSpot VM上是这样.但由于其他因素,可能会发生优化.

以下是Brian Goetz在this article中所说的内容(对于长报价而言):

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.

On the other hand,the run-time environment and JIT compiler have more
information about what classes are actually loaded,and can make much
better optimization decisions than the compiler can. If the run-time
environment knows that no classes are loaded that extend Y,then it
can safely inline calls to methods of Y,regardless of whether Y is
final (as long as it can invalidate such JIT-compiled code if a
subclass of Y is later loaded). So the reality is that while final
might be a useful hint to a dumb run-time optimizer that doesn’t
perform any global dependency analysis,its use doesn’t actually
enable very many compile-time optimizations,and is not needed by a
smart JIT to perform run-time optimizations.

final is not final any more,at least in Java 5也有一个好帖子.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读