The following list is from the google I/O talk in 2008 called \"Dalvik Virtual Machine Internals\" its a list of ways to loop over a set of objects in order from most to least e
I guess that the compiler optimizes (3) to this (this is the part where I'm guessing):
for (int i =0; i < array.length; ++i)
{
Type obj = array[i];
}
And (7) can't be optimized, since the compiler doesn't know what kind of Iterable it is. Which means that it really has to create a new Iterator
on the heap. Allocating memory is expensive. And every time you ask for the next object, it goes trough some calls.
To give a rough sketch of what is happens when (7) gets compiled (sure about this):
Iterable iterable = get_iterable();
Iterator it = iterable.iterator(); // new object on the heap
while (it.hasNext()) // method call, some pushing and popping to the stack
{
Type obj = it.next(); // method call, again pushing and popping
}