Is it slower to iterate through a list in Java like this:
for (int i=0;i
as opposed to:
I didn't look myself into the code of get()
of all List implementations so maybe what I will write is some FUD. What I have learned is that using the get(i)
in for loop will result in an iteration over the whole list over and over again each loop run. Using an Iterator (like enhanced for loop does) will just move the iterator the the next list element without iterating the whole list again.
My conclusion is that using iterators or the enhanced for loop should be more performant since using get()
will result in complexity O(n^2)
instead of O(n)
.
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! :)
Checking the size every iteration does add i
operations, but it's not a big impact on performance.
By that, I mean there is a minor difference between
int lsize = myList.size();
for(int i=0; i < lsize; i++)
{
Object o = myList.get(i);
}
Versus:
for(int i=0; i < myList.size(); i++)
{
Object o = myList.get(i);
}
But it essentially doesn't matter. Use the second one from your question for readability, among other reasons.