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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With