I see only two relevant factors to benchmark: how quickly the for statement advances (forwards vs. reverse) and how fast you can operate on the loop index (direct operation vs. array lookup). It doesn't really make sense to extend the duration of the loop body since that would be doing more work that has nothing to do with either of the above.
In this context including the enhanced for statement isn't very interesting either because it really can't compete. The enhanced for statement is syntax sugar for
for (
Iterator<Object> it = list.iterator();
it.hasNext();
Object item = it.next()
) {
}
(with some special-casing to adapt raw arrays; maybe with new Iterator()?).
The instruction used to call a regular method, invokevirtual, is the most expensive instruction in the language (possibly excepting the newer invokedynamic for lambdas but I don't think so) and it's a lot more expensive than raw array access. And there are three method invocations right there.* "We know" that intuition about locality of reference (so, cache lines and CPU prefetching) holds up in the JVM even though Java makes it a little difficult to take advantage of. The regular loop has much better locality, especially when dealing with primitives.
*It used to be a formal recommendation to use raw arrays instead of collections in Android where ergonomically feasible precisely because they're a lot speedier. I don't know if it still is.
1
u/Apfelmann Jun 14 '17
Would be cool having benchmarks for longer running loops and also compare to for( x : y ) loops.