为什么 Java 的 JIT 编译器不将所有内容转换为本机代码?
我一直在研究 Java JIT 编译器,但我无法弄清楚为什么某些代码仍然被解释。为什么 JIT 编译器不将所有内容都翻译为本机代码?翻译速度慢了很多,我错过了什么吗?
I have been looking into the Java JIT compiler and i cannot figure out why some of the code is still interpreted. Why doesn't the JIT compiler translate everything to native code? Interpretation is much slower, am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这都是一个权衡的问题,
It's all a matter of tradeoffs
如果您正在运行像 HotSpot 这样的 JVM,它会适时进行 JIT 编译,只关注频繁执行的代码。它通过计算每个代码块(或方法 - 我不确定是哪个)的频率来确定要动态优化的代码。因此,在启动时,一切都会被解释。
其背后的目的是通过只需要优化一小部分代码来允许更积极和更昂贵的优化。
If you are running a JVM like HotSpot, it JIT-compiles opportunistically, only focusing on code that executes frequently. It determines which code to optimise on the fly by counting frequency of each code block (or method — I'm not sure which). Consequently, at startup time, everything is interpreted.
The intent behind this is allow for much more aggressive and expensive optimisations by only requiring a small fraction of the code to be optimised.
两个主要原因:
因此 Java JIT 采取了一个明智的策略:在观察到相同的代码之前不要编译被运行多次,此时您有证据表明进行编译可能是值得的,并且您可以进行一些额外的优化。
Two main reasons:
Hence the Java JIT takes a sensible strategy: don't compile until you observe that the same code is being run multiple times, at which point you have evidence that doing the compilation is probably worthwhile and you are able to make some additional optimisations.
JIT 编译器使用程序执行统计信息动态优化代码。例如,“热路径”优化对程序某一部分的命中次数进行计数,并仅针对程序中频繁执行的那些部分生成机器代码。这允许 JIT 优化器将频繁执行的机器代码片段放置在一起,以便它们适合处理器的缓存。这使得 JIT 编译器的性能优于预编译的机器代码。
JIT compiler optimizes code on the fly using program execution statistics. For example, "hotpath" optimization counts the number of hits in one part of the program and generates machine code only for those parts of the code where the program is executed frequently. This allows the JIT optimizer to place pieces of frequently executed machine code close together so that they fit into the processor's cache. This allows the JIT compiler to outperform precompiled machine code.