Java – While vs For vs Iterator Performance Test
Node
This article is using the
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 :
- While Loop
- For Loop
- 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.
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.
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.
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.
Beside using for loop, are there any solutions to solve about performance time using iterator?
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 🙂
JC
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”);
}
}
}
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++;
}
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
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.
Ugh, yet more micro benchmarks.
THEY DON’T WORK.
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.
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 🙂
yes i agree with you, here is the testing i made for loop backward
https://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?