I read that the enhanced for loop is more efficient than the normal for loop here:
http://developer.android.com/guide/practices/performance.html#foreach
When I searched for the difference between their efficiency, all I found is: In case of normal for loop we need an extra step to find out the length of the array or size etc.,
for(Integer i : list){
....
}
int n = list.size();
for(int i=0; i < n; ++i){
....
}
But is this the only reason, the enhanced for loop is better than the normal for loop? In that case better use the normal for loop because of the slight complexity in understanding the enhanced for loop.
Check this for an interesting issue: http://www.coderanch.com/t/258147/java-programmer-SCJP/certification/Enhanced-Loop-Vs-Loop
Can any one please explain the internal implementation of these two types of for loops, or explain other reasons to use the enhanced for loop?
It’s a bit of an oversimplification to say that the enhanced for loop is more efficient. It can be, but in many cases it’s almost exactly the same as an old-school loop.
The first thing to note is that for collections the enhanced for loop uses an
Iterator, so if you manually iterate over a collection using anIteratorthen you should have pretty much the same performance than the enhanced for loop.One place where the enhanced for loop is faster than a naively implemented traditional loop is something like this:
In this case Loop 1 will be slower than both Loop 2 and Loop 3, because it will have to (partially) traverse the list in each iteration to find the element at position
i. Loop 2 and 3, however will only ever step one element further in the list, due to the use of anIterator. Loop 2 and 3 will also have pretty much the same performance since Loop 3 is pretty much exactly what the compiler will produce when you write the code in Loop 2.