29

(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.

Community
  • 1
  • 1
PNS
  • 19,295
  • 32
  • 96
  • 143
  • Answer 256859 does cover my question but somehow it did not pop up in the searches I did. Thanks everyone! – PNS Feb 10 '12 at 11:23

5 Answers5

74

From section 14.14.2 of the JLS:

Otherwise, the Expression necessarily has an array type, T[]. Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement. Then the meaning of the enhanced for statement is given by the following basic for statement:

T[] a = Expression;
L1: L2: ... Lm:
for (int i = 0; i < a.length; i++) {
        VariableModifiersopt Type Identifier = a[i];
        Statement
}

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.

Nicola Isotta
  • 202
  • 3
  • 10
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

You can write your own simple test, which measure the execution time.

long start = System.currentTimeMillis();
forLoop(text);
long end = System.currentTimeMillis();
long result = end - start;

result is execution time.

alnasfire
  • 720
  • 6
  • 23
  • Seemingly yes, but in reality there are too many other parameters affecting such a measurement (even the order in which the tests are executed) to consider it reliable. – PNS Feb 10 '12 at 11:29
  • 4
    Yeah, tests that measure execution time and should have a certain degree of validity are never “simple.” – Bombe Feb 10 '12 at 12:21
  • @PNS: It's still better to measure (in a realistic situation) than it is to speculate. With measurement, you can only be somewhat misled; with speculation, you can go _wildly_ wrong. – Donal Fellows Feb 15 '12 at 14:22
  • I've found that foreach's performance time is less than for loop while executing same block of code. – ved Feb 06 '13 at 09:33
3

Since you are using an array type, the performance difference wouldn't matter. They would end up giving the same performance after going through the optimization funnel.

But if you are using ADTs like List, then the forEachLoop is obviously the best choice compared to multiple get(i) calls.

Navneeth G
  • 7,255
  • 1
  • 15
  • 18
3

You should choose the option which is more readable almost every time, unless you know you have a performance issue.

In this case, I would say they are guaranteed to be the same.

The only difference is you extra check for text.length which is likely to be slower, rather than faster.

I would also ensure text is never null statically. e.g. using an @NotNull annotation. Its better to catch these issues at compile/build time (and it would be faster)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

There is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. For details follow this post.

Community
  • 1
  • 1
Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73