Java – While vs For vs Iterator Performance Test

Node
This article is using the endTime - startTime method to measure the performance of a loop, it ignores the JVM warm up optimization, the result may not consistent or accurately.

A better way is using the OpenJDK JMH framework to do the benchmark testing, because it will take care of the JVM warm up concerns automatically, see this example – Java JMH benchmark tutorial

A simple Java code to test the performance of the following looping methods :

  1. While Loop
  2. For Loop
  3. Iterator Loop

In Java, just compare the endTime and startTime to get the elapsed time of a function.


	long startTime = new Date().getTime();
	// call something else
	long endTime = new Date().getTime();
	long difference = endTime - startTime;
	System.out.println("Elapsed time in milliseconds: " + difference);

While vs For vs Iterator

A Java code to loop a List which containing 1, 5, 10 and 15 million records.

LoopSimpleTest.java

package com.mkyong.benchmark.bk;

import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class LoopSimpleTest {

    private static List<String> DATA_FOR_TESTING = Arrays.asList(createArray());

    public static void main(String[] argv) {

        LoopSimpleTest obj = new LoopSimpleTest();

        obj.loopIterator();
        obj.loopFor();
        obj.loopWhile();

    }

    public void loopFor() {
        System.out.println("\n--------- For Loop -------\n");
        long startTime = new Date().getTime();

        for (int i = 0; i < DATA_FOR_TESTING.size(); i++) {
            String s = DATA_FOR_TESTING.get(i);
        }

        long endTime = new Date().getTime();
        long difference = endTime - startTime;
        System.out.println("For - Elapsed time in milliseconds: " + difference);
    }

    public void loopWhile() {
        System.out.println("\n--------- While Loop -------\n");
        long startTime = new Date().getTime();

        int i = 0;
        while (i < DATA_FOR_TESTING.size()) {
            String s = DATA_FOR_TESTING.get(i);
            i++;
        }

        long endTime = new Date().getTime();
        long difference = endTime - startTime;
        System.out.println("While - Elapsed time in milliseconds: " + difference);
    }

    public void loopIterator() {
        System.out.println("\n--------- Iterator Loop -------\n");
        long startTime = new Date().getTime();

        Iterator<String> iterator = DATA_FOR_TESTING.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
        }

        long endTime = new Date().getTime();
        long difference = endTime - startTime;
        System.out.println("Iterator - Elapsed time in milliseconds: " + difference);
    }

    private static String[] createArray() {
        String sArray[] = new String[15_000_000];
        for (int i = 0; i < 15_000_000; i++) {
            sArray[i] = "Array " + i;
        }
        return sArray;
    }

}

Output


D:\test>java -Xms1024m -Xmx1024m ArrayToList

--------- Iterator Loop -------

Iterator - Elapsed time in milliseconds: 390


--------- For Loop --------

For - Elapsed time in milliseconds: 234


--------- While Loop -------

While - Elapsed time in milliseconds: 234

The iterator loop is the slowest, and the difference between for loop and while loop isn't that significant.

References

  1. Java JMH benchmark tutorial

About the Author

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

Comments

avatar
24 Comment threads
9 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
22 Comment authors
DoctorDendriteJay AskrenHow to remove all null elements from a ArrayList or String Array? | Ask Programming & Technologyadgrepalex Recent comment authors
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.