Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

methods in foreach and for loops in java

Tags:

java

android

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?

like image 529
Kevin Westwood Avatar asked Apr 18 '12 20:04

Kevin Westwood


People also ask

What is forEach method in Java?

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.

What is the difference between for loop and forEach loop in Java?

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.


1 Answers

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.

like image 75
Ted Hopp Avatar answered Oct 11 '22 07:10

Ted Hopp