Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does shorthand for loop cache the iterable's reference?

I am likely trying to be over-efficient, but I have been wondering which of the following two code samples would execute more quickly.

Assume that you have a reference to an object which contains an ArrayList of Strings and you want to iterate through that list. Which of the following is more efficient (even if only marginally so)?

for(String s : foo.getStringList())
    System.out.println(s);

Or

ArrayList<String> stringArray = foo.getStringList();
for(String s : stringArray)
    System.out.println(s);

As you can see, the second loop initializes a reference to the list instead of calling for it every iteration, as it seems the first sample does. Unless this notion is completely incorrect and they both function the same way because the inner workings of Java create their own reference variable.

So my question is, which is it?

like image 299
StrongJoshua Avatar asked Apr 23 '15 02:04

StrongJoshua


1 Answers

There's no difference, because both loops only end up getting and maintaining a reference to an Iterator for the expression at the start of the loop. Here's an excerpt from the Java Language Specification:

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier =
        (TargetType) #i.next();
    Statement
}
like image 83
that other guy Avatar answered Oct 20 '22 12:10

that other guy