简体   繁体   中英

How to induce or help Java Compilers to optimize code?

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

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.

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.

... 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM