Click here to Skip to main content
15,867,594 members
Articles / General Programming / Performance
Tip/Trick

For Vs Foreach - Benchmark 2013

Rate me:
Please Sign up or sign in to vote.
4.93/5 (11 votes)
25 Jan 2013CPOL2 min read 80.9K   175   17   20
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 

Image 1

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: 

C#
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: 

C#
// 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); 
C#
// 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:

C#
StringBuilder sb = new StringBuilder(); 

Sample of For Loop Test: 

C#
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 

C#
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)


Written By
Software Developer
Other Other
Programming is an art.

Comments and Discussions

 
QuestionSo basically you have proved C# is slow Pin
shiftwik24-Dec-16 21:13
shiftwik24-Dec-16 21:13 
GeneralWhich construct is faster depends on what you're iterating over. Pin
Member 1024450319-May-16 20:40
Member 1024450319-May-16 20:40 
AnswerThe value of these results is low Pin
Sergey Alexandrovich Kryukov14-May-15 8:28
mvaSergey Alexandrovich Kryukov14-May-15 8:28 
GeneralMy vote of 5 Pin
Thornik29-Jan-13 8:05
Thornik29-Jan-13 8:05 
GeneralMy vote of 3 Pin
Raju_B27-Jan-13 19:51
Raju_B27-Jan-13 19:51 
QuestionTesting for SPList Objects Pin
Pinguwien25-Jan-13 3:21
Pinguwien25-Jan-13 3:21 
AnswerRe: Testing for SPList Objects Pin
adriancs25-Jan-13 4:20
mvaadriancs25-Jan-13 4:20 
QuestionIncorrect graph title Pin
riced24-Jan-13 10:00
riced24-Jan-13 10:00 
AnswerRe: Incorrect graph title Pin
adriancs25-Jan-13 4:15
mvaadriancs25-Jan-13 4:15 
SuggestionIList and IList<> interface Pin
Daniele Rota Nodari24-Jan-13 9:54
Daniele Rota Nodari24-Jan-13 9:54 
GeneralRe: IList and IList<> interface Pin
adriancs25-Jan-13 4:16
mvaadriancs25-Jan-13 4:16 
GeneralRe: IList and IList<> interface Pin
Daniele Rota Nodari25-Jan-13 5:03
Daniele Rota Nodari25-Jan-13 5:03 
GeneralRe: IList and IList<> interface Pin
adriancs27-Jan-13 23:23
mvaadriancs27-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
FatCatProgrammer23-Jan-13 7:53 
GeneralMy vote of 3 Pin
Harry Neethling22-Jan-13 9:04
Harry Neethling22-Jan-13 9:04 
GeneralRe: My vote of 3 Pin
adriancs22-Jan-13 20:28
mvaadriancs22-Jan-13 20:28 
GeneralMy vote of 3 Pin
Fred Flams22-Jan-13 3:32
Fred Flams22-Jan-13 3:32 
GeneralRe: My vote of 3 Pin
adriancs22-Jan-13 3:46
mvaadriancs22-Jan-13 3:46 
GeneralRe: My vote of 3 Pin
Fred Flams22-Jan-13 3:53
Fred Flams22-Jan-13 3:53 
GeneralRe: My vote of 3 Pin
adriancs22-Jan-13 20:29
mvaadriancs22-Jan-13 20:29 
Hi, I have include the ArrayList in the test.
and the code is rewrite to run test more properly.
and new information is updated. Smile | :)

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.