如何诱导或帮助Java编译器优化代码?

发布于 2024-10-02 03:06:14 字数 72 浏览 8 评论 0原文

我想知道 Java 编译器的哪些优化通常会因为不清晰或写得不好而被阻止(或未被检测到),以及会犯什么样的常见错误来混淆编译器的代码

I'm wondering which optimizations of Java Compilers can be usually blocked (or not detected) because of non-clear or badly written code, and what kind of commong mistakes are made that obfuscates the code for the Compiler

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

仅此而已 2024-10-09 03:06:14

请理解,现代运行时环境(实际的 Java 命令)并不是天真地一一执行 Java 字节码,而是进行非常繁重的处理以编译为实际的机器代码。

这意味着没有特殊原因使字节码特别智能或优化,因为 JRE 无论如何都会给出相同的结果。对于移动 Java 设备,解释器不太智能,并且存在内存限制,ProGuard 系统允许进行相当多的优化转换。您可能会发现这些很有趣。

Please understand that modern runtime environments (the actual Java command) is not executing the java bytecodes naively one by one, but is doing very heavy processing to compile to actual machine code.

This means that there is no special reason to make the bytecode particularly smart or optimized, as the JRE gives the same results anyway. For mobile Java devices, where the interpreter is less smart, and memory constraints are present, the ProGuard system allows for quite a bit of optimizing transformations. You might find these interesting.

诗化ㄋ丶相逢 2024-10-09 03:06:14

JIT 编译器通常针对常见编码模式和用例进行优化。最好的选择是遵守常见的惯例、模式和习惯用法。尝试“为编译器优化代码”可能会导致代码实际上更难优化。

我建议尝试使代码清晰且富有表现力,并让编译器完成其工作。

JIT compilers are typically optimized for common coding patterns and use cases. Your best bet is to adhere to common conventions, patterns, and idioms. Trying to "optimize code for the compiler" might result in code that is actually harder to optimize.

I would advice to just try to make your code clear and expressive, and let the compiler do its job.

多情癖 2024-10-09 03:06:14

...我想知道在编码时是否有一些非常常见的错误可以通过多加注意来避免。

对于 Sun 的 HotSpot JVM,一般意义上您可能犯的唯一错误是尝试以棘手的方式(可能)做事,相信这样可以使您的代码更快。最好只编写简单的代码。我从 HotSpot 团队的一位资深人士那里看到了这个建议。

最佳实践是将优化留给 JIT 编译器,并且仅在分析器告诉您有问题时才尝试进行微优化。

(您应该避免一些众所周知的事情,例如使用异常进行流量控制、在循环中进行字符串连接或尝试进行自己的内存管理。但这些可能比您感兴趣的级别更高。)

... I wanted to know if there were very common mistakes that could be avoided with a bit more of attention when coding.

For Sun's HotSpot JVMs, the only mistake that you can make in the general sense is to try to do things in tricky ways (possibly) in the belief that it makes your code faster. It is best to just write simple code. I've seen this advice from someone senior in the HotSpot team.

Best practice is to leave optimization to the JIT compiler, and only attempt to micro-optimize if the profiler tells you that you have a problem.

(There are well know things you should avoid, like using exceptions for flow control, doing string concatenation in a loop, or trying to do your own memory management. But these are probably higher level than you are interested in.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文