Java 优化:(Hotspot/Dalvik)返回常量的最终方法的优化?
谁能告诉我 Hotspot 或 Dalvik 是否足够聪明,可以内联调用返回常量(静态最终)int 值的最终方法?理想情况下,方法调用将被常量替换。这可能是在类加载时或通过 JIT。
这对我正在处理的一些代码的设计有影响。
Can anyone tell me if either Hotspot or Dalvik is smart enough to inline calls to a final method returning a constant (static final) int value? Ideally the method call would be replaced by the constant. This might either be at class load time or through JIT.
This has implications in the design of some code I'm working on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为答案是“不,由于
final
关键字的存在或不存在,优化不会发生”,至少在 HotSpot VM 上是这样。但由于其他因素,优化可能会发生。以下是 Brian Goetz 在本文中所说的话(抱歉长引用):
还有一篇很好的文章,解释为什么final 不再是final,至少在Java 5 中。
I would think that the answer is "no, optimization will not happen because of absence or presence of the
final
keyword", at least on the HotSpot VM. But optimization will likely happen because of other factors.Here's what Brian Goetz says in this article (sorry for the long quote):
There's also a good post why final is not final any more, at least in Java 5.
内联是 JIT 编译器在检测到热点时可能会执行的操作,该热点是字节代码中经常被调用的方法。可能值得花费一些 CPU 时间将字节代码编译成机器代码。
JIT 编译器很有可能会内联一个
final
方法(因为它不能被覆盖)。如果该方法只返回一个常量值,那么机会会更好。但我的理解是 - 如果调用方法不是热点,那么它将不会被编译,并且不会内联
final
方法。(德语信息源)
Inlining is something the JIT compiler might do if it detects a hot spot, a method in the byte code that has been called that often that it probably worth spending some CPU time on compiling the byte code into machine code.
There's a very good chance that the JIT compiler will inline a
final
method (as it can't be overwritten). And chances will be even better if that method just returns a constant value.But it's my understanding - if the calling method is not a hot spot, then it will not be compiled and there'll be no inlining of the
final
methods.(Information source in german language)
或者,Soot 有望针对这种情况优化 Java 字节码。
Alternatively, Soot is expected to optimize Java bytecode for such case.