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--------- 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--------- 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);
		long lWhileEndTime = new Date().getTime();
		System.out.println("End: " + lWhileEndTime);
		long lWhileDifference = lWhileEndTime - lWhileStartTime;
		System.out.println("While - Elapsed time in milliseconds: "
				+ lWhileDifference);
	static String[] createArray() {
		String sArray[] = new String[15000000];
		for (int i = 0; i < 15000000; i++)
			sArray[i] = "Array " + i;
		return sArray;


D:\test>java -Xms1024m -Xmx1024m ArrayToList
--------- Iterator Loop -------
Start: 1232435614372
End: 1232435614763
Iterator - Elapsed time in milliseconds: 390
--------- For Loop --------
Start: 1232435614763
End: 1232435614997
For - Elapsed time in milliseconds: 234
--------- While Loop -------
Start: 1232435614997
End: 1232435615232
While - Elapsed time in milliseconds: 234

Performance Test Result (in milliseconds)


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 ~
Tags :

About the Author

Founder of Mkyong.com and HostingCompass.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.


  • Pingback: How to remove all null elements from a ArrayList or String Array? | Ask Programming & Technology()

  • 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 third repeat of all the tests there was no difference.

    Unfortunately I need my loop for a rare on-the-fly reset. It may never get run, and almost certainly will only be called once in the run.

  • alex

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

  • 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 test… which atomic comparsion is faster?
    Javas native a==b or (a^b)==0x0

    Try it for yourself and you WILL BE suprised :)


  • Pingback: How to remove all null elements from a ArrayList or String Array? | BlogoSfera()

  • http://msnl 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 guess?”);
    sColor = reader.readLine();

    System.out.println(“Congratulations! ” + sName);
    catch (IOException e){
    System.out.println(“Error reading from user”);



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


  • 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 …

  • 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

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

  • http://adiguba.developpez.com/ 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…


  • 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 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.


  • Pingback: [Java] While loop, For loop and Iterator Performance Test « Kyhuang's Blog()

  • 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.



  • http://www.pageheat.com/heat/sexhinam.com Ha Golladay

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

  • Pingback: Tagz | "While loop, For loop and Iterator Performance Test - Java | Java" | Comments()

  • Ran Biron

    Ugh, yet more micro benchmarks.

  • Pingback: Why many Java performance tests are wrong | StuQ.nl()

  • 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

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

      • mkyong

        can you give some explanation here about what are you trying to say?

  • http://richard-wilkinson.co.uk 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.

    • mkyong

      yes i agree with you, here is the testing i made for loop backward


    • 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 :)

  • http://architecturerules.org Mike

    Thanks for the stats.

  • BlogReader

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

  • 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.

    • mkyong

      sorry , can you elaborate more about it?