Which set of conditions is better for looping in Java? I feel they will do the same thing but I'm not sure if I'm not seeing something under the hood.
For(int i = 0; i < array.length; i++) { }
For(int i = 0; i <= array.length-1; i++) { }
Which set of conditions is better for looping in Java? I feel they will do the same thing but I'm not sure if I'm not seeing something under the hood.
For(int i = 0; i < array.length; i++) { }
For(int i = 0; i <= array.length-1; i++) { }
The fact that you commonly see both two forms is most likely due to a combination of the following:
Differences in style preferences. The first form is more concise, and some people would prefer it for that reason.
Differences in the way the programmer was thinking about the problem.
Differences in the way the programmer thinks that the reader will think about the problem. (Like "I know that array indexes go to array.length - 1
and I want the reader to see that I have taken that into account.")
A (probably mistaken) belief that one version is more efficient than the other.
I say "probably mistaken" because the consensus is that a modern Java JIT compiler is likely to optimize the two forms into native code that has equivalent performance. I am stating this without providing evidence1 because I am not aware of any counter-evidence2.
1 - Evidence could be obtained by proper benchmarking, or by carefully analyzing the native code emitted by the JIT compiler. Examining bytecodes won't prove anything.
2 - If there was counter-evidence ... that this made a difference ... I claim that it would be common knowledge!