Wednesday, July 15, 2009

Performance Test for Java While loop, For loop and Iterator

Do you wonder which of the following methods are the faster 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 of data in While loop, For loop and Iterator loop. It’s will calculate and display the elapsed time in output.

Here is the performance test source code

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

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

{

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

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 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 performance different.

13 comments:

  1. FYI, always use System.nanoTime() when benchmarking. At least when the result will be below one second. The normal only has a resolution of 5-15ms depending on platform which will make a significant percentage difference for small durations.

    Cheers,
    Mikael

    ReplyDelete
  2. 1) What VM was this run against and was it in client or server mode?
    2) You did not allow the JVM to warm up, profile, and execute optimized byte-code.
    3) I agree with using System#nanoTime()
    4) You should read "How NOT To Write A Microbenchmark" by Cliff Click.

    ReplyDelete
  3. hmm.. sorry if that sounded critical. I was in analysis mode, not commenting mode. :)

    ReplyDelete
  4. Hi Mikael thanks for the tip.

    Ben all your comments are welcome.

    ReplyDelete
  5. Did you consider adding the enhanced for loop too?

    ReplyDelete
  6. Simple swap the position of the (last) "while"-test to the first one and this will be magically the slowest one ...

    Do not forget warmup! And read the comments of

    http://karussell.wordpress.com/2009/05/21/microbenchmarking-java-compare-algorithms/

    ReplyDelete
  7. Forgive my ignorance Ben, but what did you mean by "..you did not allow the jvm to warm up" ?

    ReplyDelete
  8. While old, this article has a nice explanation of warm-up and its impact on micro-benchmarks.

    ReplyDelete
  9. Ben, Thanks for the fantastic URL. While I made this measurements I haven't considered the measurement phase. It could have resulted in wrong benchmarking results?!!!

    ReplyDelete
  10. It may have, but even then your results show the correct conclusion: use the cleanest form, as performance shouldn't be a consideration. If you want to experiment for fun and try to do it right, then consider following Sun's guide.

    ReplyDelete
  11. Thank you ben for all your valuable comments.

    ReplyDelete
  12. Thanks for the link Ben, it was very informative.

    ReplyDelete
  13. This comment has been removed by a blog administrator.

    ReplyDelete