最终方法是否内联? [英] final methods are inlined?

查看:55
本文介绍了最终方法是否内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以自动内联Java最终方法?

Are Java final methods automatically inlined?

很多书说是的,很多书说不!

Many books says yes many books says no!!!

推荐答案

有趣的问题,促使我进一步研究.我发现2条有趣的话-

Interesting question, prompted me to look into it further. 2 interesting remarks I found -

  • 1 评论 内联是一个错误:
  • 1 comment that automatic inlining is a bug:

与许多暗示相反 提示,声明为final的方法不能 被编译器安全地内联, 因为该方法可能有一个 在运行时进行非最终声明.

Contrary to the implication of many tips, methods declared as final cannot be safely inlined by the compiler, because the method could have a non-final declaration at runtime.

要了解原因,假设编译器看起来 在A类和B类中,并且 子类C并看到最终方法 在A内嵌到C.但是然后 在运行时为A加载的版本 和B不同,方法是 在A中不是最终的,而在B中则被覆盖. 然后,C使用错误地内联 版本. T

To see why, suppose the compiler looks at class A and subclass B, and sub-subclass C and sees a final method in A which it inlines into C. But then at runtime the versions loaded for A and B are different and the method is not final in A, and overridden in B. Then C uses the incorrectly inlined version. T

更有权威性的是,来自 sun白皮书,该方法可以保留为虚拟状态,

And, a bit more authoritatively, from a sun whitepaper, writing that methods can be left virtual,

由于Java HotSpot VM可以自动内联绝大多数虚拟方法调用,因此可以显着降低这种性能损失,并且在许多情况下可以完全消除.

Because the Java HotSpot VM can automatically inline the vast majority of virtual method invocations, this performance penalty is dramatically reduced, and in many cases, eliminated altogether.

有关该机制的更多信息直接引用.

Here's a more direct reference on the mechanism.

这篇关于最终方法是否内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆