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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Assuming this is what you meant:
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:
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.