Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of traditional for loop vs Iterator/foreach in Java

Is there any performance testing results available in comparing traditional for loop vs Iterator while traversing a ArrayList,HashMap and other collections?

Or simply why should I use Iterator over for loop or vice versa?

like image 788
Harish Avatar asked Dec 10 '09 07:12

Harish


People also ask

Which is faster traditional for loop or foreach in Java?

The FOR loop without length caching and FOREACH work slightly faster on arrays than FOR with length caching. Array. Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays.

Which is faster iterator or for loop in Java?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.

Which is faster foreach or for loop?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Which is better foreach or for loop in Java?

The key difference between for Loop and foreach loop is that the for loop is a general purpose control structure while the foreach loop is an enhanced for loop that is applicable only to arrays and collections.


1 Answers

Assuming this is what you meant:

// traditional for loop for (int i = 0; i < collection.size(); i++) {   T obj = collection.get(i);   // snip }  // using iterator Iterator<T> iter = collection.iterator(); while (iter.hasNext()) {   T obj = iter.next();   // snip }  // using iterator internally (confirm it yourself using javap -c) for (T obj : collection) {    // snip } 

Iterator is faster for collections with no random access (e.g. TreeSet, HashMap, LinkedList). For arrays and ArrayLists, performance differences should be negligible.

Edit: I believe that micro-benchmarking is root of pretty much evil, just like early optimization. But then again, I think it's good to have a feeling for the implications of such quite trivial things. Hence I've run a small test:

  • iterate over a LinkedList and an ArrayList respecively
  • with 100,000 "random" strings
  • summing up their length (just something to avoid that compiler optimizes away the whole loop)
  • using all 3 loop styles (iterator, for each, for with counter)

Results are similar for all but "for with counter" with LinkedList. All the other five took less than 20 milliseconds to iterate over the whole list. Using list.get(i) on a LinkedList 100,000 times took more than 2 minutes (!) to complete (60,000 times slower). Wow! :) Hence it's best to use an iterator (explicitly or implicitly using for each), especially if you don't know what type and size of list your dealing with.

like image 121
sfussenegger Avatar answered Sep 20 '22 07:09

sfussenegger