Recently I bumped into a situation where a static code analysis tool (PMD) complainted about a switch
statement that had too few branches. It suggested turning it into an if statement, that I did not wanted to do because I knew that soon more cases will be added. But I wondered if the javac
performs such an optimization or not. I decompiled the code using JAD but it showed still a switch. Is it possible that this is optimized runtime by the JIT?
Update: Please do not be misleaded by the context of my question. I'm not asking about PMD, I'm not asking about the need for micro-optimisation, etc. The question is clearly only this: does the current (Oracle 1.6.x) JVM implementation contain a JIT that deals with switches with too few branches or not.
The way to determine how the JIT compiler is optimizing switch statements is either:
Note that like all questions related to performance and optimization, the answer depends on the hardware platform and the JVM vendor and version.
Reference: Disassemble Java JIT compiled native bytecode
If this Question is "mere idle curiosity", so be it.
However, it should also be pointed out that rewriting your code to use switch
or if
for performance reasons is probably a bad idea and/or a waste of time.
It is probably a waste of time because the chances are that the difference in time (if any) between the original and hand optimized versions will be insignificant.
It is a bad idea because, your optimization may only be helpful for specific hardware and JVM combinations. On others, it may have no effect ... or even be an anti-optimization.
In short, even if you know how the JIT optimizer handles this, you probably shouldn't be taking it into account in your programming.
(The exception of course is when you have a real measurable performance problem, and profiling points to (say) a 3-branch switch
as being one of the bottlenecks.)
If you compiled it in debug mode, it is normal that when you decompile it, you still get the switch. Otherwise, any debugging attempt would miss some information such as line number and the original instruction flow.
You could thus try to compile in production mode and see what the decompilation result would be.
However, a switch statement, especially if it is expected to grow, is generally considered as a code smell and should be evaluated as a good candidate for a refactoring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With