Click here to Skip to main content
13,045,379 members (111,398 online)
Click here to Skip to main content
Add your own
alternative version

Stats

48.5K views
141 downloads
17 bookmarked
Posted 21 Jan 2013

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

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

You may also be interested in...

Comments and Discussions

 
QuestionSo basically you have proved C# is slow Pin
shiftwik24-Dec-16 21:13
membershiftwik24-Dec-16 21:13 
GeneralWhich construct is faster depends on what you're iterating over. Pin
Member 1024450319-May-16 20:40
memberMember 1024450319-May-16 20:40 
AnswerThe value of these results is low Pin
Sergey Alexandrovich Kryukov14-May-15 8:28
mvpSergey Alexandrovich Kryukov14-May-15 8:28 
GeneralMy vote of 5 Pin
Thornik29-Jan-13 8:05
memberThornik29-Jan-13 8:05 
GeneralMy vote of 3 Pin
Kamarajub27-Jan-13 19:51
memberKamarajub27-Jan-13 19:51 
QuestionTesting for SPList Objects Pin
Pinguwien25-Jan-13 3:21
memberPinguwien25-Jan-13 3:21 
AnswerRe: Testing for SPList Objects Pin
adriancs25-Jan-13 4:20
mvpadriancs25-Jan-13 4:20 
QuestionIncorrect graph title Pin
riced24-Jan-13 10:00
memberriced24-Jan-13 10:00 
AnswerRe: Incorrect graph title Pin
adriancs25-Jan-13 4:15
mvpadriancs25-Jan-13 4:15 
SuggestionIList and IList<> interface Pin
Daniele Rota Nodari24-Jan-13 9:54
memberDaniele Rota Nodari24-Jan-13 9:54 
GeneralRe: IList and IList<> interface Pin
adriancs25-Jan-13 4:16
mvpadriancs25-Jan-13 4:16 
GeneralRe: IList and IList<> interface Pin
Daniele Rota Nodari25-Jan-13 5:03
memberDaniele Rota Nodari25-Jan-13 5:03 
GeneralRe: IList and IList<> interface Pin
adriancs27-Jan-13 23:23
mvpadriancs27-Jan-13 23:23 
QuestionAlmost no difference between For Loop and Foreach Loop. Foreach Loop seems to be a bit faster. Pin
FatCatProgrammer23-Jan-13 7:53
memberFatCatProgrammer23-Jan-13 7:53 
GeneralMy vote of 3 Pin
Harry Neethling22-Jan-13 9:04
memberHarry Neethling22-Jan-13 9:04 
GeneralRe: My vote of 3 Pin
adriancs22-Jan-13 20:28
mvpadriancs22-Jan-13 20:28 
GeneralMy vote of 3 Pin
Fred Flams22-Jan-13 3:32
memberFred Flams22-Jan-13 3:32 
GeneralRe: My vote of 3 Pin
adriancs22-Jan-13 3:46
mvpadriancs22-Jan-13 3:46 
GeneralRe: My vote of 3 Pin
Fred Flams22-Jan-13 3:53
memberFred Flams22-Jan-13 3:53 
GeneralRe: My vote of 3 Pin
adriancs22-Jan-13 20:29
mvpadriancs22-Jan-13 20:29 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 26 Jan 2013
Article Copyright 2013 by adriancs
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid