How is Java's for loop code generated by the compiler

Viewed 19798

How is Java's for loop code generated by the compiler?

For example, if I have:

for(String s : getStringArray() )
{
   //do something with s
}

where getStringArray() is a function that returns the Array I want to loop on, would function be called always or only once? How optimal is the code for looping using this construct in general?

4 Answers

JDK 1.4 introduced the RandomAccess interface. It is meant to give a hint to algorithms when, for a given List implementation, it is more efficient to iterate through:

for (int i = 0, n = list.size(); i < n; i++) {
    list.get(i);
}

than

for (Iterator i = list.iterator(); i.hasNext(); ) {
   i.next();
}

Does the foreach loop take this into account? Or does it completely ignore the fact that a given Iterable is in fact a List?

It should be noted that this would imply that adding a (iterable instanceof List && iterable instanceof RandomAccess) test and a downcast to List would work, which would add an overhead that's not always worth it and could be considered a premature optimization for a compiler syntactic sugar feature.

Related