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();
}
It's always better to use the iterator instead of indexing. This is because iterator is most likely optimzied for the List implementation while indexed (calling get) might not be. For example LinkedList is a List but indexing through its elements will be slower than iterating using the iterator.
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 following code:
Gives following output on my system:
I'm running Ubuntu 12.10 alpha with OracleJDK 1.7 update 6.
In general HotSpot optimizes a lot of indirections and simple reduntant operations, so in general you shouldn't worry about them unless there are a lot of them in seqence or they are heavily nested.
On the other hand, indexed get on LinkedList is much slower than calling next on iterator for LinkedList so you can avoid that performance hit while retaining readability when you use iterators (explicitly or implicitly in for-each loop).
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.
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.
Yes,
for-each
variant is faster than than normalindex-based-for-loop
.for-each
variant usesiterator
. So traversing is faster than normalfor
loop which is index based.This is because
iterator
are optimized for traversing, because it is pointing to just before the next element and just after the previous element. One of the reason for beingindex-based-for-loop
to be slow is that, it have to calculate and move to the element position each time which is not with theiterator
.