android – methods in foreach and for loops in java-ThrowExceptions

Exception or error:

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?

How to solve:

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 another way 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
}

This will be substantially faster (the Android docs linked to above say by a factor of 3) if aList happens to be an ArrayList, but is likely to be slower (possibly by a lot) for a LinkedList. It all depends on exactly what kind of List implementation class aList is.

Leave a Reply

Your email address will not be published. Required fields are marked *