Thanks Stephan.. but putting them in anonymous block makes the whole code as "dead block" which JVM may not even have to execute. I know it's bad programming but should programmer avoid this or can JVM take care of optimizing this is what I am looking for.
Nothing is happening inside the code to change the state of the system. It's basically no effect code. Would it make sense to execute this code? [ May 31, 2006: Message edited by: Purushothaman Thambu ]
Originally posted by Purushothaman Thambu: Would it make sense to execute this code?
But your original code was quite different -- it included a constructor call and some other unknown code. That can't be optimized away. Talking about compiler optimizations is tricky enough without changing the code under discussion half-way through!
Ernest, The orginal code is about avoiding 99 conditional checks. What will happen if a conditional block is true only at first iteration. I am not clear how anonymous block will improve things. The second anonmyous block code can be considered as a dead block since the code is not changing the state of the system (Heap) but just consumes the cpu cycles.
I have no idea why Stefan recommended that to you, but it's not really related to your original question, so let's forget about it for now.
I'd guess for the specific case you've shown that Hotspot might indeed be smart enough to do the optimization you've shown. But remember that Hotspot won't do anything until it sees that a particular method is being called frequently enough to warrant optimization, so it's generally best to do these kinds of code-motion optimizations yourself if they don't obfuscate the code -- and indeed, here it makes the code shorter and clearer.
Further, even if Hotspot is able to do this kind of thing, it probably couldn't do it if the loop upper limit is a variable or function return value; it's never good to try to second-guess undocumented software!