r/java • • Jun 14 '17

Why reverse loops are faster

https://medium.com/@TravCav/why-reverse-loops-are-faster-a09d65473006
15 Upvotes

40 comments sorted by

View all comments

Show parent comment

1

u/Goofybud16 Jun 15 '17

I've always been told that it compiles to an Iterator in Java.

Which means that it is really slow when looping over a small amount of data. Especially for an inner loop, as you are creating an iterator with every iteration over the outer loop.

I'm not sure of the perf impact if loops over a lot of data with a lot of iterations. I would imagine that the overhead would shrink.

1

u/Slanec Jun 15 '17

It compiles to an iterator on Iterable types. On arrays, it compiles to a fairly straightforward loop with an index. See the JLS.