Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java's for-each call an embedded method (that returns the collection) for every iteration?

Tags:

java

foreach

If there is a method call MyClass.returnArray() and I iterate over the array using the for-each construct (also called the "enhanced for" loop):

for (ArrayElement e : MyClass.returnArray()) {    //do something } 

will then the returnArray() method be called for every iteration?

like image 944
d56 Avatar asked Jul 21 '10 10:07

d56


People also ask

What does a for-each loop do?

A for-each loop is a loop that can only be used on a collection of items. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array.

What is the advantage of using forEach over traditional for loop?

The forEach() method provides several advantages over the traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of a regular stream. Since you are operating on stream, it also allows you to filter and map elements.

Does for-each loop use iterator?

for-each is an advanced looping construct. Internally it creates an Iterator and iterates over the Collection.

Why forEach method is added to each collection?

The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.


2 Answers

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.

like image 59
Péter Török Avatar answered Nov 02 '22 03:11

Péter Török


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.

like image 36
Andreas Dolk Avatar answered Nov 02 '22 04:11

Andreas Dolk