1

When using for-each loop I often do not create a temporary variable like

int[] arr = method_returning_array();
for (element : arr) {
    // whatever
{

Instead, I shortcut it as follows:

for (element : method_returning_array()) {
    // whatever
{

Is the latter way of doing it bad (or not optimal) for any reason?

caasdads
  • 409
  • 4
  • 12
  • What do you mean with "not optimal"? Performance? Measure it! Code readability? Somewhat opinion-based. – Seelenvirtuose Nov 17 '18 at 14:25
  • I mean everything. Performance and Code readability and whatever else. Any information from any aspect on that is highly welcome! – caasdads Nov 17 '18 at 21:59

2 Answers2

1

If method_returning_array() returns large array read the footnote too.

Enhanced for loop is just a syntactic sugar, it can take any subtype of Iterable or Array.

In your case, since method is returning array it will be compiled as:

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
}

Where a and i are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

And method_returning_array() is only called once.

IMPORTANT:

But there is a related bug,2 which got fixed in Java 10, which may impact you if method_returning_array() returns really large array. Workaround is to use traditional for loop:

for (int i = 0; i < a.length; i++) 

For details, read

Anurag Sharma
  • 2,409
  • 2
  • 16
  • 34
0

Actually in both cases you create temporary local to the for loop variable.

int[] arr = method_returning_array();
for (int element : arr) {
    // whatever
}

arr is available after for loop

for (int element : method_returning_array()) {
    // whatever
}

method_returning_array() result is not available after for loop

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35