Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: Iterating through a List in Java

Tags:

java

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 } 
like image 799
syker Avatar asked Apr 15 '10 00:04

syker


People also ask

Which Java loop is faster?

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.

What type of loop is most effective to iterate over a list?

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.

Which is faster for loop or forEach in Java?

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.


1 Answers

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! :)

like image 165
Pablo Fernandez Avatar answered Oct 17 '22 01:10

Pablo Fernandez