How inefficient is that:
List<Object> getList(){
return new LinkedList<Object>();
}
void foo(){
for(Object o: getList()){
do something with o;
}
}
in compare with that:
List<Object> getList(){
return new LinkedList<Object>();
}
void foo(){
List<Object> os = getList();
for(Object o: os){
do something with o;
}
}
There won’t be any perceptible difference.
I’ve compiled the following code:
The bytecodes for
foo1andfoo2are as follows:As you can see for yourself, the bytecodes for the two loops are identical. The only difference is that
foo2stores and loads the list reference in a local variable at the start.One might argue that a better optimizing compiler may be able to eliminate
osaltogether, producing identical code for both functions.