Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

For Vs Foreach - Benchmark 2013

0.00/5 (No votes)
25 Jan 2013 1  
Performance Comparison of For Loop and Foreach Loop

Update (23/02/2017)

There is another benchmark result published on 13 May 2016 at [C#: For Vs ForEach Vs While] which the benchmark tested with more data type and more details findings. You might want to have a read on it. The benchmark shows different times consumed for different data type.

Introduction   

I have seen lots of arguments and different points of view about which is better practice among For Loop and Foreach Loop

YearResearcherArticle.NET Based
2004Chester RagelFOREACH Vs. FOR (C#)
- CodeProject.com
.NET 1.1
2004CodecutterTo foreach or not to foreach that is the question
- blogs.msdn.com
.NET 1.1
2006Dustin CampbellPerformance of foreach vs. List.ForEach
- diditwith.net
.NET 2.0
2008Adrian VintuForeach Loop VS For Loop
- adrianvintu.com
.NET 3.5
2013steinkrauzOnce upon a time there was a difference between 'for' and 'foreach'
- lj.rossia.org
.NET 4.0
2016David LozinskiC#: For Vs ForEach Vs While
- cc.davelozinski.com
Not specified.

From the outcomes of the findings from the previous programmers, some of the conclusions of the researches were conflicting each other, and thus, this shows that the way .NET work with For Loop and Foreach Loop has changed from years to years. It seems that the development team of .NET Framework has improved and modified the workout logic of For Loop and Foreach throughout different version of milestone of .NET Framework releases.

After reading the valuable information from the articles, I have decided to do benchmark, to compare the performance between For Loop and Foreach Loop in figures. 

The Benchmark Result (2013)

Measured in miliseconds.  Default collection length: 30000000 . I try to increase the length, but receive exception of System.OutOfMemoryException. 

 

Data TypeCollection TypeLoop TypeTest 1Test 2Test 3Average
intint[]For88.005183.004783.004884.672
intint[]Foreach83.004782.004781.004782.005
intList<int>For89.005184.004883.004885.338
intList<int>Foreach98.005698.005798.005698.006
intArrayList<int>For188.0107182.0104182.0104184.011
intArrayList<int>Foreach445.0254444.0254445.0254444.692
classclass[]For98.005692.005292.005394.005
classclass[]Foreach93.005393.005392.005292.672
classList<class>For107.0061107.0061108.0062107.339
classList<class>Foreach136.0078138.0078137.0079137.008
classArrayList<class>For195.0111195.0111196.0112195.344
classArrayList<class>Foreach446.0255443.0254446.0255 445.025

Chart 

Conclusion

Speed of Collections

 

  1. Array (Fastest)
  2. List 
  3. ArrayList (Slowest) 

 

Data Type - Operation 

Array

Almost no difference between For Loop and Foreach Loop. Foreach Loop seems to be a bit faster. 

List

For Loop is slightly faster than Foreach Loop

ArrayList

For Loop is about more than 2 times faster speed than Foreach Loop. 

Codes Used to Run the Test 

Declare Collections: 

static int[] intArray = null;
static List<int> intList = null;
static ArrayList intArrayList = null; 
static SampleClass[] scArray = null;
static List<SampleClass> scList = null;
static ArrayList scArrayList = null; 
static int LengthTest = 30000000; 

Initializing Collection: 

// int  
byte[] ba = new byte[LengthTest];
Random rd = new Random();
rd.NextBytes(ba);
intArray = new int[ba.Length];
for (int h = 0; h < ba.Length; h++)
{
    intArray[h] = ba[h];
} 
intList = new List<int>();
intList.AddRange(intArray);
intArrayList = new ArrayList(intArray); 
// class object 
DateTime scStart = DateTime.Now;
scArray = new SampleClass[LengthTest];
for (int i = 0; i < scArray.Length; i++)
    scArray[i] = new SampleClass();
scList = new List<SampleClass>(scArray);
scArrayList = new ArrayList(scArray); 

 

A StringBuilder to collect information:

StringBuilder sb = new StringBuilder(); 

Sample of For Loop Test: 

static void TestIntArrayFor()
{
    string section = "int[] For Loop Test - Length = " + intArray.Length; 
    List<TimeSpan> lstTimespan = new List<TimeSpan>();
    sb.AppendLine(section);
    for (int round = 0; round < Round; round++)
    {
        DateTime start = DateTime.Now;
        int total = 0;
        for (int i = 0; i < intArray.Length; i++)
        {
            total += intArray[i];
        }
        lstTimespan.Add(DateTime.Now - start);
        sb.AppendLine("Test " + (round + 1) + " : " + lstTimespan[round].TotalMilliseconds.ToString()); 
    }
    double ds = 0;
    for (int b = 0; b < lstTimespan.Count; b++)
    {
        ds += lstTimespan[b].TotalMilliseconds;
    }
    sb.AppendLine("Average: " + (ds / 3).ToString("0.###") + " miliseconds");
    sb.AppendLine();
} 

Sample of Foreach Loop Test 

static void TestClassArrayForeach()
{
    string section = "Class[] Foreach Loop Test - Length = " + scArray.Length;
    List<TimeSpan> lstTimespan = new List<TimeSpan>();
    sb.AppendLine(section);
    for (int round = 0; round < Round; round++)
    {
        DateTime start = DateTime.Now;
        long total = 0;
        foreach(SampleClass sc in scArray)
        {
            total += sc.Number;
        }
        lstTimespan.Add(DateTime.Now - start);
        sb.AppendLine("Test " + (round + 1) + " : " + lstTimespan[round].TotalMilliseconds.ToString()); 
    }
    double ds = 0;
    for (int b = 0; b < lstTimespan.Count; b++)
    {
        ds += lstTimespan[b].TotalMilliseconds;
    }
    sb.AppendLine("Average: " + (ds / 3).ToString("0.###") + " miliseconds"); 
} 

 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here