Is it slower to iterate through a list in Java like this:
for (int i=0;i<list.size();i++) { .. list.get(i) }
as opposed to:
for (Object o: list) { ... o }
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
Using an iterator, or using a foreach loop (which internally uses an iterator), guarantees that the most appropriate way of iterating is used, because the iterator knows about how the list is implemented and how best go from one element to the next.
The FOR loop without length caching and FOREACH work slightly faster on arrays than FOR with length caching. Array. Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays.
I assume you ask out of pure curiosity and won't cite Knuth (somebody probably will).
I believe that once your code gets compiled, it doesn't make a difference. It does make a difference before (example 2 is a lot more readable and concise), so go for number 2 and do not care about the rest.
Just my 2 cents
EDIT
Note your code in snippet number 1 calculates list.size()
every time the loop runs, that could make it even slower than number 2
YET ANOTHER EDIT
Something I had to double check, Joshua Bloch recommends using for each
loops (see item 46 of Effective Java). I believe that ends all kinds of discussions. Thanks Josh! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With