What, if any, is the performance difference between the following two loops?
for (Object o: objectArrayList) {
o.DoSomething();
}
and <
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.
Even with something like an ArrayList or Vector, where "get" is a simple array lookup, the second loop still has additional overhead that the first one doesn't. I would expect it to be a tiny bit slower than the first.
The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the nuances of the for-each loop.
I think the article is now here: new location
The link shown here was dead.
By the variable name objectArrayList
, I assume that is an instance of java.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 the List#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.
foreach makes the intention of your code clearer and that is normally preferred over a very minor speed improvement - if any.
Whenever I see an indexed loop I have to parse it a little longer to make sure it does what I think it does E.g. Does it start from zero, does it include or exclude the end point etc.?
Most of my time seems to be spent reading code (that I wrote or someone else wrote) and clarity is almost always more important than performance. Its easy to dismiss performance these days because Hotspot does such an amazing job.
public class FirstJavaProgram {
public static void main(String[] args)
{
int a[]={1,2,3,45,6,6};
// Method 1: this is simple way to print array
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
// Method 2: Enhanced For loop
for(int i:a)
{
System.out.print(i+" ");
}
}
}