What, if any, is the performance difference between the following two loops?
for (Object o: objectArrayList) {
o.DoSomething();
}
and
for (int i=0; i<objectArrayList.size(); i++) {
objectArrayList.get(i).DoSomething();
}
What, if any, is the performance difference between the following two loops?
for (Object o: objectArrayList) {
o.DoSomething();
}
and
for (int i=0; i<objectArrayList.size(); i++) {
objectArrayList.get(i).DoSomething();
}
The only way to know for sure is to benchmark it, and even that is not as simple as it may sound. The JIT compiler can do very unexpected things to your code.
From Item 46 in Effective Java by Joshua Bloch :
Accepted answer answers the question, apart from the exceptional case of ArrayList...
Since most developers rely on ArrayList(atleast I believe so)
So I am obligated to add the correct answer here.
Straight from the developer documentation:-
The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections that implement the Iterable interface and for arrays. With collections, an iterator is allocated to make interface calls to hasNext() and next(). With an ArrayList, a hand-written counted loop is about 3x faster (with or without JIT), but for other collections the enhanced for loop syntax will be exactly equivalent to explicit iterator usage.
There are several alternatives for iterating through an array:
zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the loop.
one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.
two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.
So, you should use the enhanced for loop by default, but consider a hand-written counted loop for performance-critical ArrayList iteration.
By the variable name
objectArrayList
, I assume that is an instance ofjava.util.ArrayList
. In that case, the performance difference would be unnoticeable.On the other hand, if it's an instance of
java.util.LinkedList
, the second approach will be much slower as theList#get(int)
is an O(n) operation.So the first approach is always preferred unless the index is needed by the logic in the loop.