Is it slower to iterate through a list in Java like this:
for (int i=0;i
as opposed to:
Created a microbenchmark for the question and was surprised to see for-each runing 2x-3x faster than an indexed loop. The only explanation I have is that for-each version might not require range checks which are made by ArrayList.get(int index).
For very small lists (10 elements) the result was about the same. For 100 elements for-each is 1.5x faster, for 10000-100000 elements it is faster 2x-3x times.
The tests are run on a random dataset and checksums are being verified at the end, so JIT chearing is very unlikely to take place in these.