Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

For Vs Foreach - Benchmark 2013

, 25 Jan 2013
Rate this:
Please Sign up or sign in to vote.
Performance Comparison of For Loop and Foreach Loop

Introduction   

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

Year Researcher Article .NET Based
2004 Chester Ragel FOREACH Vs. FOR (C#)
- CodeProject.com
.NET 1.1
2004 Codecutter To foreach or not to foreach that is the question
- blogs.msdn.com
.NET 1.1
2006 Dustin Campbell Performance of foreach vs. List.ForEach
- diditwith.net
.NET 2.0
2008 Adrian Vintu Foreach Loop VS For Loop
- adrianvintu.com
.NET 3.5
2013 steinkrauz Once upon a time there was a difference between 'for' and 'foreach'
- lj.rossia.org
.NET 4.0

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  

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

 

Data Type Collection Type Loop Type Test 1 Test 2 Test 3 Average
int int[] For 88.0051 83.0047 83.0048 84.672
int int[] Foreach 83.0047 82.0047 81.0047 82.005
int List<int> For 89.0051 84.0048 83.0048 85.338
int List<int> Foreach 98.0056 98.0057 98.0056 98.006
int ArrayList<int> For 188.0107 182.0104 182.0104 184.011
int ArrayList<int> Foreach 445.0254 444.0254 445.0254 444.692
class class[] For 98.0056 92.0052 92.0053 94.005
class class[] Foreach 93.0053 93.0053 92.0052 92.672
class List<class> For 107.0061 107.0061 108.0062 107.339
class List<class> Foreach 136.0078 138.0078 137.0079 137.008
class ArrayList<class> For 195.0111 195.0111 196.0112 195.344
class ArrayList<class> Foreach 446.0255 443.0254 446.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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

adriancs
Software Developer
Malaysia Malaysia
Writing programs is an art.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberThornik29-Jan-13 8:05 
GeneralMy vote of 3 PinmemberKamarajub27-Jan-13 19:51 
QuestionTesting for SPList Objects PinmemberPinguwien25-Jan-13 3:21 
AnswerRe: Testing for SPList Objects Pinmvpadriancs25-Jan-13 4:20 
QuestionIncorrect graph title Pinmemberriced24-Jan-13 10:00 
AnswerRe: Incorrect graph title Pinmvpadriancs25-Jan-13 4:15 
SuggestionIList and IList<> interface PinmemberDaniele Rota Nodari24-Jan-13 9:54 
GeneralRe: IList and IList<> interface Pinmvpadriancs25-Jan-13 4:16 
GeneralRe: IList and IList<> interface [modified] PinmemberDaniele Rota Nodari25-Jan-13 5:03 
GeneralRe: IList and IList<> interface Pinmvpadriancs27-Jan-13 23:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 26 Jan 2013
Article Copyright 2013 by adriancs
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid