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?
The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised.
The for loop is a control structure for specifying iteration that allows code to be repeatedly executed. The foreach loop is a control structure for traversing items in an array or a collection. A for loop can be used to retrieve a particular set of elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With