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?
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:In the second,
aList.size()will be called every time the test is evaluated. For readability, it would be better to code it as:However, per the Android docs (on a page no longer available that I could find, but archived here) this will be slower. Assuming that you aren’t changing the list size inside the loop,
the fastestanother way would be to pull out the list size ahead of the loop:This will be substantially faster (the Android docs linked to above say by a factor of 3) if
aListhappens to be anArrayList, but is likely to be slower (possibly by a lot) for aLinkedList. It all depends on exactly what kind ofListimplementation classaListis.