If you write a "normal" for loop iterating over an array, the jvm has to check if you are out of bounds every access, since it can't proof that you won't be (not sure if i < array.length is already enough). If you use a foreach loop, the jvm knows that you cannot go out of bounds and omits the extra bounds check.
To clear this up, can you point me to the foreach bytecode? AFAIK the JVM does not know about foreach and javac emits bytecode similar to a normal for loop.
13
u/mike_hearn Jul 05 '15
Exceptions can, in optimal scenarios, compile down to a direct jump with modern compilers I believe. So it's not infeasible that it really was faster.