Nayan Nayan - 1 month ago 11
Java Question

Performance of ArrayList iteration in Java

What happens when we write the following code?

for(String name: getNameList()) {
// do something with name
}


Is
getNameList()
function called in each iteration or only first time? I'm curious to know because my
getNameList()
function is costly. Is it better to write the following code instead of the above one?

List<String> nameList = getNameList();
for(String name: nameList) {
// do something with name
}


How do this work?

Answer

There's no difference. Your original loop is equivalent to this:

for(Iterator<String> iter = getNameList().iterator(); iter.hasNext();) {
    String name = iter.next();
    // do something with name
}