开发者

How to induce or help Java Compilers to optimize code?

开发者 https://www.devze.com 2023-01-23 22:57 出处:网络
I\'m wondering which optimizations of Java Compiler开发者_Go百科s can be usually blocked (or not detected) because of non-clear or badly written code, and what kind of commong mistakes are made that o

I'm wondering which optimizations of Java Compiler开发者_Go百科s 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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消