Kevin Westwood Kevin Westwood - 6 months ago 10
Java Question

methods in foreach and for loops in java

My question is regarding optimization in java using the Android compiler. Will map.values() in the following be called every iteration, or will the Android compiler optimize it out.

LinkedHashMap<String, Object> map;

for (Object object : map.values())
{
//do something with object
}


Likewise here is another example. will aList.size() be called every iteration?

List<Object> aList;

for (int i = 0; i < aList.size(); i++)
{
object = aList.get(i);
//do something with i
}


And after all this, does it really matter if it calls the methods every iteration? Does Map.values(), and List.size() do much of anything?

Answer

In the first example, map.values() will be evaluated once. According to the Section 14.4.2 of the Java Language Specification, it is equivalent to:

for (Iterator<Object> i = map.values().iterator(); i.hasNext(); ) {
    Object object = i.next();
    // do something with object
}

In the second, aList.size() will be called every time the test is evaluated. For readability, it would be better to code it as:

for (Object object : aList) {
    // do something with object
}

However, per the Android docs, this will be slower. Assuming that you aren't changing the list size inside the loop, the fastest would be to pull out the list size ahead of the loop:

final int size = aList.size();
for (int i = 0; i < size; i++)
{
    object = aList.get(i);
    //do something with i
}
Comments