views:

121

answers:

5

His,

I have a question to the advanced for loop in java. If there is a method call Method.returnArray() and I iterate over the array with for (ArrayElement e : Method.returnArray()) { //do smth }

will the .returnArray() be called by every iteration?

Thanks.

A: 

No, it will be called once. It's not like the termination condition of a standard for loop, which gets evaluated on every iteration.

Eyal Schneider
+4  A: 

No, it won't. The result of the first call will be stored in the compiled code in a temporary variable.

From Effective Java 2nd. Ed., Item 46:

Note that 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.

Péter Török
Great book, great book.
Jean-Philippe Caruana
A: 

No, I don't think so. I would have noticed it "on production" (with bad performances) since.

So, Go go go with foreach loops !

Jean-Philippe Caruana
+1  A: 

No.

The for loop is just syntactic sugar. It behaves differently depending on whether or not it is applied to an Array argument or an object implementing the Iterable interface.

For Iterable objects, the loop expands to something like this:

Iterator<ArrayElement> iter = iterableObject.iterator();
while (iter.hasNext()) {
   ArrayElement e = iter.next();
   // do smth
}

What your example code is actually doing is something like this:

Object[] temp = Method.returnArray();
for ( int i = 0; i < temp.length; i++ ) {
  ArrayElement e = (ArrayElement) temp[i];
  // do smth
}     
Lucas
This is perfectly true for all subclasses of `Iterable` but the advanced for loop can be used with arrays too, and I guess, that was the point of the question. It's still 'syntactical sugar' but a bit different.
Andreas_D
+1  A: 

From the java language spec:

EnhancedForStatement:
    for ( VariableModifiersopt Type Identifier: Expression) Statement

and later on:

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

This is (in pseudo code) the equivalent of the advanced for loop for arrays. And it is made clear, that the Expression is evaluated once and the resulting array is assigned to T[] a.

So it's perfectly safe to use even complex expressions in the advanced for loop statement.

Andreas_D