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)
.