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?

  1. While Loop
  2. For Loop
  3. 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.

Note
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 ~

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
DoctorDendrite
Guest
DoctorDendrite

Your graph isn’t properly labeled. I should be able to tell by looking at just the graph itself and not the heading above it what the numbers represent.

Jay Askren
Guest
Jay Askren

I noticed you are including in your timing the time to print the start time. I moved the print statement to right before the printing of the end time so it is no longer being timed. I also moved the iterator so it is last instead of first. With these changes, the timings are almost identical. Any differences in speed are removed by the JIT compiler once Java gets warmed up.

trackback
How to remove all null elements from a ArrayList or String Array? | Ask Programming & Technology

[…] While loop, For loop and Iterator Performance Test […]

adgrep
Guest
adgrep
I also am doubtful about the validity of such tests. Calling the same suite of tests several times gives big reductions in later run timings. I ‘had been told’ to remove the for condition for (int i = 0; ; i++) and catch a bounds exception to end the loop. This made things worse. But I did an obvious optimization – evaluating the list size once, i.e. int end = lList.size(); for (int i = 0; i < end; i++) { expecting it to make no difference because of runtime optimization. This did help the first time, but by the… Read more »
alex
Guest
alex

Beside using for loop, are there any solutions to solve about performance time using iterator?

Jan Cajthaml
Guest
Jan Cajthaml
Your performance (stress) test is wrong. You are forgetting about “warm up time” so your result may be depended on other applications running on your computer during test. To solve that simply add some random computations before the main test, then let JVM “sleep” for a while then do some more calculations and THEN begin your test. Its also good to mention that any stress test that doesn’t iterate at least 10 000 000 times (in one test) is misleading. Keep up good work but think sometimes about what you are doing. Btw I have an idea for you to… Read more »
trackback
How to remove all null elements from a ArrayList or String Array? | BlogoSfera

[…] While loop, For loop and Iterator Performance Test […]

Watt
Guest
Watt
Hello MKyong; I am practicing on while loop.I want to terminate the while loop after I enter the string variables 4 or 5 times. Could you advise me? I will appreciated. public static void main(String[] args) { // first we define our input streams. InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input); int count=0; String sName ; String sColor; try { System.out.println(“what is your name?”); sName = reader.readLine(); // then will ask for the color System.out.println(“What color do you guess?”); sColor = reader.readLine(); while (sColor.compareToIgnoreCase(“red”) != 0) //while loop control { System.out.println(“let’s try again: What color do you… Read more »
Jan Cajthaml
Guest
Jan Cajthaml

try this :)

int numberOfInputsCounter = 1;

while (sColor.compareToIgnoreCase(“red”) != 0 && numberOfInputsCounter<5) //while loop control
{
System.out.println(“let’s try again: What color do you guess?”);
sColor = reader.readLine();
numberOfInputsCounter++;

}

john
Guest
john

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

antano
Guest
antano

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

NuxlyStardust
Guest
NuxlyStardust

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();
}

adiGuba
Guest
adiGuba

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++

tomasz
Guest
tomasz
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… Read more »
trackback
[Java] While loop, For loop and Iterator Performance Test « Kyhuang's Blog
Sam
Guest
Sam

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

Ha Golladay
Guest
Ha Golladay

Many thanks for that details. It’s much appreciated! Best regards.

trackback
Tagz | "While loop, For loop and Iterator Performance Test - Java | Java" | Comments

[…] [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 […]

Ran Biron
Guest
Ran Biron

Ugh, yet more micro benchmarks.
THEY DON’T WORK.

trackback
Why many Java performance tests are wrong | StuQ.nl

[…] 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 […]

andrew
Guest
andrew


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];
}
}

andrew
Guest
andrew


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++];
}
}

Richard Wilkinson
Guest
Richard Wilkinson

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.

Jan Cajthaml
Guest
Jan Cajthaml

And “have you been told” that HashSet if faster than RandomAccessList or that QuickSort is faster then GnomeSort or that Java does not have Destructor or that you cannot pass method in parameter of other method in Java or there is nothing like week references and strong references in Java or you cannot acces specific object in Java Heap with pointer?

Me too and it too was a lie.

Dig in deeper and you will be suprised what Java is capable of :)

Mike
Guest
Mike

Thanks for the stats.

BlogReader
Guest
BlogReader

Try changing the order of the loops in your code and see if that changes their times

Jeff Martin
Guest
Jeff Martin

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.