While loop, For loop and Iterator Performance Test – Java
Do you wonder which of the following methods are the fastest way to loop through a list or collection before?
- While Loop
- For Loop
- Iterator Loop
Performance Test – While , For and Iterator
Here i create a simple program to loop through a List with 1,5,10 and 15 millions records in While loop, For loop and Iterator loop.
Here’s the source code to run the simulating the testing date.
package com.mkyong.core; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; public class ArrayToList { public static void main(String[] argv) { String sArray[] = createArray(); // convert array to list List lList = Arrays.asList(sArray); System.out.println("\n--------- Iterator Loop -------\n"); long lIteratorStartTime = new Date().getTime(); System.out.println("Start: " + lIteratorStartTime); // iterator loop Iterator<String> iterator = lList.iterator(); while (iterator.hasNext()) { String stemp = iterator.next(); } long lIteratorEndTime = new Date().getTime(); System.out.println("End: " + lIteratorEndTime); long lIteratorDifference = lIteratorEndTime - lIteratorStartTime; System.out.println("Iterator - Elapsed time in milliseconds: " + lIteratorDifference); System.out.println("\n-------END-------"); System.out.println("\n--------- For Loop --------\n"); long lForStartTime = new Date().getTime(); System.out.println("Start: " + lForStartTime); // for loop for (int i = 0; i < lList.size(); i++) { String stemp = (String) lList.get(i); } long lForEndTime = new Date().getTime(); System.out.println("End: " + lForEndTime); long lForDifference = lForEndTime - lForStartTime; System.out.println("For - Elapsed time in milliseconds: " + lForDifference); System.out.println("\n-------END-------"); System.out.println("\n--------- While Loop -------\n"); long lWhileStartTime = new Date().getTime(); System.out.println("Start: " + lWhileStartTime); // while loop int j = 0; while (j < lList.size()) { String stemp = (String) lList.get(j); j++; } long lWhileEndTime = new Date().getTime(); System.out.println("End: " + lWhileEndTime); long lWhileDifference = lWhileEndTime - lWhileStartTime; System.out.println("While - Elapsed time in milliseconds: " + lWhileDifference); System.out.println("\n-------END-------"); } static String[] createArray() { String sArray[] = new String[15000000]; for (int i = 0; i < 15000000; i++) sArray[i] = "Array " + i; return sArray; } }
Output
D:\test>java -Xms1024m -Xmx1024m ArrayToList --------- Iterator Loop ------- Start: 1232435614372 End: 1232435614763 Iterator - Elapsed time in milliseconds: 390 -------END------- --------- For Loop -------- Start: 1232435614763 End: 1232435614997 For - Elapsed time in milliseconds: 234 -------END------- --------- While Loop ------- Start: 1232435614997 End: 1232435615232 While - Elapsed time in milliseconds: 234 -------END-------
Performance Test Result (in milliseconds)

Conclusion
Well… the result show that the Iterator mechanism is the slowest method to loop through a list. There’s not much performance different between For and While loop.
Iterator provides a very handy way to loop through a list or collection, but it is slower than For and While loop. Please be remind that the different is just in milliseconds (not even 1 second for 15 millions of data looping). So, just choose any looping mechanism you want, there’s not much different.
15 millions of data and java -Xms1024m -Xmx1024m is the limit of my computer , may be someone can help me test this in 20 millions of data? Thanks ~
book b;
for(int i=0; i<list.size(); i++)
{b = list.get(i); system.out.printIn(b)}
convert the following for loop into the enhanced for loop
can anyone help me …
plzzzzz
Refer to this “four ways to loop a list in Java“
strangely on E5620 linux box iterator is faster than the rest:
Iterator – Elapsed time in milliseconds: 188
For – Elapsed time in milliseconds: 483
While – Elapsed time in milliseconds: 482
tried running with -Xincgc:
Iterator – Elapsed time in milliseconds: 170
For – Elapsed time in milliseconds: 367
While – Elapsed time in milliseconds: 367
As stated above, you should integrate a For loop to read the iterator. This is a much better way to go, and takes approximately the same time as the While loop without the iterator.
for (Iterator iterator = lList.iterator(); iterator.hasNext();){
String stemp = iterator.next();
}
Hello ! (sorry for my bad english)
Use a true ArrayList instead of Arrays.asList() !
Arrays.asList() provide a basic and generic Iterator, not really adapted to the data-structure.
ArrayList (and many List’s implementation) use an real and optimized Iterator that provide similar result than for/while.
And after for fun try with a LinkedList : Iterator is still performant but for/while will be very catastrophic…
Iterator is generally the more valuable and simpliest choice…
a++
It seems like you don’t understand what List is.
List is just an interface, nothing more. Yet, you have prepared some test for just one, speciffic implementation of a list and use this results as it was true for all types of lists. So very wrong.
In your example you took instance of list from Arrays.asList(anArray[]). This list is nothing more than a wrapped array, and get(index) is nothing more than access to the anArray[index]. In this case using iterator is just overkill, as it has some additional logic.
But if you take LinkedList, be patient. On my laptop “for loop” on just 100.000 (one hundred thousand) elements took 7 seconds, while an iterator took 7 milliseconds. Doubling size of an array quadruples iteration time through LinkedList using get(index).
Why? Because LinkedList is literally a linked list. There are no indexes, just references to the next element on list. If you call get(X), you will have to get to the Xth element one by one, passing all elements before. That is very ineffective and time consuming. On the other hand, using an iterator, you just take reference to the next element on list.
If you want to know what to use to iterate, for/while + get(index) or an iterator, check if list implements RandomAccess interface. If yes, you can use get(index). In no, better use iterator.
Regards
Tomasz
[...] http://www.mkyong.com/java/while-loop-for-loop-and-iterator-performance-test-java/ [...]
Hi mkyong,
nice to see a quick comparison boiled down, but I would suggest one addition…
your Iterator loop IS a While loop, so how about a distinction between While Iterator and For Iterator as below:
for (Iterator iterator = lList.iterator(); iterator.hasNext();)
{
String stemp = iterator.next();
}
this also localizes the scope of the Iterator to the loop itself.
pz,
sam
Many thanks for that details. It’s much appreciated! Best regards.
[...] [upmod] [downmod] While loop, For loop and Iterator Performance Test – Java | Java (mkyong.com) 1 points posted 3 months, 3 weeks ago by SixSixSix tags java imported saved by [...]
Ugh, yet more micro benchmarks.
THEY DON’T WORK.
[...] example, some days ago a ‘performance test’ on while loops, iterators and for loops was posted. This test is wrong and inaccurate. I will use this test as an example, but there are [...]
public static void test2(String[] lst)
{
int size = (lst.length & -1);
int i = 0;
while (i < size)
{
String s;
s = lst[i++];
s = lst[i++];
}
while (i < lst.length)
{
String s = lst[i];
}
}
public static void test2(String[] lst) {
int size = (lst.length & -2);
int i = 0;
while (i < size) {
String s;
s = lst[i++];
s = lst[i++];
}
while (i < lst.length) {
String s = lst[i++];
}
}
can you give some explanation here about what are you trying to say?
I had been told that looping through a loop backwards is faster, since you are always comparing to 0 which is apparently faster, but i’m not sure how accurate that is. Tests I have done don’t really show any improvement.
yes i agree with you, here is the testing i made for loop backward
http://www.mkyong.com/java/reverse-loop-versus-forward-loop-in-performance-java/
Thanks for the stats.
Try changing the order of the loops in your code and see if that changes their times
Thanks for tips, ya… it did change result a bit, however the stats i show is taking by the 5 execution average time. So the result should be correct.
Why Many Java Performance Tests are Wrong
http://java.dzone.com/articles/why-many-java-performance-test
My favorite loop is: for(int i=0, iMax=list.size(); i<iMax; i++) …
I wonder how that compares to an iterator loop, given that you take the list size method out of the loop.
sorry , can you elaborate more about it?