Possible Duplicate:
for loop optimization
Let's say we want to loop over the characters of a string s
. I'd say the following code is more or less the default.
for( int i = 0; i < s.length(); i++ ) {
doSomethingWith( s.charAt( i ) );
}
Question #1: Why do I often see the following?
final int length = s.length();
for( int i = 0; i < length; i++ ) {
doSomethingWith( s.charAt( i ) );
}
At first sight this seems reasonable since the inequality is evaluated on every iteration. I would however expect the VM to optimize this anyway, since strings are immutable. Any thoughts? And what if we iterate over a mutable structure (that's not referenced by any other thread)? And what if length()
is not guaranteed to run in O(1)?
Question #2: Some people seem to think substituting ++i
for i++
speeds up the code. Are they right? Again this is not what I'd expect, but I'm simply not sure.
We all know not to optimize prematurely. At the same time, if we can produce slightly faster code at hardly any expense, we'd be silly not to. Of course one could argue that both "optimizations" hurt readability, but in my opinion the damage is so small that it would be justified in certain circumstances.
I tried to measure any differences in performance, but it's hard to get conclusive results. Although this should settle it for any specific application, I'm aiming for insight and a general answer here.
(Although I wrote this with the HotSpot VM in mind it could be interesting also to consider other platforms, like mobile devices.)