Performance comparison of different for loops in java

For loop is very common control flow statement in programming languages such as java. I am not going to describe the basics of “for loop” as it is beyond the scope of this article and most of us are already well aware of this.

In this post, I will list down various ways to use for loop in day-to-day programming habits and then I will compare them against a similar set of data for their relative performances.

Different ways to use for loop

I am listing down 4 different ways in my knowledge. If you know any other way also, please let me know through a comment.

1) For each statement

In this technique, advanced for each statement introduced in java 5 is used. Learn this also as your next core java interview question.

private static List<Integer> list = new ArrayList<>();
for(Integer i : list)
{
	// do other stuff
}

2) Using list.size() in condition

private static List<Integer> list = new ArrayList<>();
for(int j = 0; j < list.size() ; j++)
{
	//do stuff
}

3) Initialize another local variable with size

private static List<Integer> list = new ArrayList<>();
int size = list.size();
for(int j = 0; j < size ; j++)
{
	//do stuff
}

4) Initialize the initial value of counter to size of list

private static List<Integer> list = new ArrayList<>();
for(int j = list.size(); j > size ; j--)
{
	//do stuff
}

Comparing the performance of all types

I am creating an arraylist and populate it with 1 crore Integer instances. Then I will iterate through the list using all four ways. This way we will be able to understand the different in performance.

Execution environment:

  • Java 7
  • Eclipse Juno
package com.howtodoinjava.demo.core;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ForLoopPerformanceTest
{
	private static List<Integer> list = new ArrayList<>();
	private static long startTime;
	private static long endTime;
	static
	{
		for(int i=0; i < 1_00_00_000; i++)
		{
			list.add(i);
		}
	}
	@SuppressWarnings("unused")
	public static void main(String[] args)
	{
		//Type 1
		startTime = Calendar.getInstance().getTimeInMillis();
		for(Integer i : list)
		{
			//
		}
		endTime = Calendar.getInstance().getTimeInMillis();
		System.out.println("For each loop :: " + (endTime - startTime) + " ms");

		//Type 2
		startTime = Calendar.getInstance().getTimeInMillis();
		for(int j = 0; j < list.size() ; j++)
		{
			//
		}
		endTime = Calendar.getInstance().getTimeInMillis();
		System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");

		//Type 3
		startTime = Calendar.getInstance().getTimeInMillis();
		int size = list.size();
		for(int j = 0; j < size ; j++)
		{
			//System.out.println(j);
		}
		endTime = Calendar.getInstance().getTimeInMillis();
		System.out.println("Using [int size = list.size(); int j = 0; j < size ; j++] :: " + (endTime - startTime) + " ms");

		//Type 4
		startTime = Calendar.getInstance().getTimeInMillis();
		for(int j = list.size(); j > size ; j--)
		{
			//System.out.println(j);
		}
		endTime = Calendar.getInstance().getTimeInMillis();
		System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
	}
}

When above program runs, following is the output in console:

For each loop :: 110 ms
Using collection.size() :: 37 ms
Using [int size = list.size(); int j = 0; j < size ; j++] :: 4 ms
Using [int j = list.size(); j > size ; j--] :: 1 ms

Clearly the last two ways are way ahead in terms of performance, while for each statement [type 1] is most expensive operation if compared with other three.

Update:

Reason for difference in performance

Last two flavors type 3 and 4 have a very little difference and should be considered as same. They both fetch the size of collection initially. And then uses this size value in loop for checking the condition.

Type 2 uses size() method call every time and thus on runtime it brings a little overhead. Though JVM optimizes this code as inline call and other optimizations also and size method is simply a getter for size attribute of instance of list. Even though it brings a few more statements to execute at machine level code and which makes the difference.

Type 1 is costliest one and simple reasoning is the use of iterator internally created in for each loop. Creating an iterator and calling iterator.get() adds up to most of cost which is not involved in direct access in other three types.

Happy Learning !!

Lokesh has written 269 articles

I have 7 Years of rich experience in java technology. This has only increased my hunger to learn more. In this blog, i will be writing on different topics occasionally, and would love to engage in some meaningful serious discussions with you folks.

13 thoughts on “Performance comparison of different for loops in java

  1. Fla says:

    Effectively, some tests where wrong (type4) and the it tests nothing if value is not accessed…

    But, something else has not been taken in advice with these tests : I’have added tests at startup of my swing application and the order of the tested methods changes the results.

    I think the memory used by previous tests objects should be garbaged during next test… Then i have added System.gc(); before each tests and results are now really differents :

    Using [Iterator iter = list.iterator(); iter.hasNext();] :: 42 ms : TOTAL = -2014260032
    Using [Integer i : list] :: 45 ms : TOTAL = -2014260032
    Using [int j = 0; j = 0 ; j--] :: 54 ms : TOTAL = -2014260032
    Using [int j = 0; j < size ; j++] :: 48 ms : TOTAL = -2014260032

  2. Also, the for-each loop runs significantly faster in cases such as a LinkedLIst, where the data is not stored in a sequential space in memory. In fact, it takes FOREVER (not literally) to use the non-for-each loops on a LinkedList.
    Having a fair understanding of how what you’re using works is fairly important to knowing how to optimize your code.

  3. Vo2 says:

    Well …

    1)
    If you make a loop, you obviously need to access the values …
    So add Integer i = list.get(j) for types >=2

    2)

    Your Type 4 may need to be debugged …
    1 + 2 =>
    Type 1 is something le 25% slower than the 3 others
    (no differences between them)

  4. I have searched for the performance of loop over the internet and no-one article says about the low performance of first loop(i.e. for-each loop). Moreover many people have given the JAVA doc specification saying that:——-
    “The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays. Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand, programmers don’t always do so.”

    1. Hi Shivam,

      Please refer to http://stackoverflow.com/questions/6839494/enhanced-for-loop-performance-worse-than-traditional-indexed-lookup.

      I can give you 10 more links which hints for slower performance.

      The reason “for-each” loop is thought better is because of its readability. Its easier to write and understand the statement. The difference for looping a large collection is a rare condition and also the time advantage is not very attractive [but its there, you can verify yourself] .

      1. Rajesh says:

        If we are dealing with collections, and trying to address each of the collection object in that case for each loop is faster. Instead of using the increment variable “i” to get the object at index “i”.

Want to ask any question? Or suggest anything?