(A question for those who know well the JVM compilation and optimization tricks… 🙂
Is there any of the “for” and “foreach” patterns clearly superior to the other?
Consider the following two examples:
public void forLoop(String[] text)
{
if (text != null)
{
for (int i=0; i<text.length; i++)
{
// Do something with text[i]
}
}
}
public void foreachLoop(String[] text)
{
if (text != null)
{
for (String s : text)
{
// Do something with s, exactly as with text[i]
}
}
}
Is forLoop faster or slower than foreachLoop?
Assuming that in both cases the text array did not need any do sanity checks, is there a clear winner or still too close to make a call?
EDIT: As noted in some of the answers, the performance should be identical for arrays, whereas the “foreach” pattern could be slightly better for Abstract Data Types like a List. See also this answer which discusses the subject.
From section 14.14.2 of the JLS:
In other words, I’d expect them to end up being compiled to the same code.
There’s definitely a clear winner: the enhanced for loop is more readable. That should be your primary concern – you should only even consider micro-optimizing this sort of thing when you’ve proved that the most readable form doesn’t perform as well as you want.