For Loop vs ForEach Loop

Programming C#

Everyone knows both for and foreach loops. Now which one of them is faster?

One could "argue" that a for loop is about integer operations while a foreach loop involves objects. And "of course" Integer operations do performe faster than handling objects.

But that's not the hole truth.  First, for loops are not necessarily about Integer operations:

for (float i=3.14159265; i<58.2458; i=+.00123)

while on the other hand a foreach could also simply just loop over Integers.

So let's compare fair - int for versus int foreach loop:

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ConsAppForForEach
{
internal class Program
{
private static void Main(string[] args)
{
List<Int32> Count = new List<int>();
long avgTicksFor = 0;
long avgTicksForEach = 0;

for (int i = 0; i < 1000000; i++)
{
Count.Add(i);
}

List<Int32> lst1 = new List<Int32>();
List<Int32> lst2 = new List<Int32>();

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < Count.Count; i++)
{
lst1.Add(i);
}
sw.Stop();
avgTicksFor += sw.ElapsedTicks;

Console.WriteLine("For Loop : " + sw.ElapsedTicks);
sw.Restart();

foreach (int a in Count)
{
lst2.Add(a);
}
sw.Stop();
avgTicksForEach += sw.ElapsedTicks;

Console.WriteLine("ForEach Loop: " + sw.ElapsedTicks);
Console.ReadLine();
}
}
}

For Loop : 60411
ForEach Loop: 84130

The output will of course depend on the hardware where this codes runs and also on how busy the CPU is working on other threads when executing loop #1 and loop #2 (and this even includes the possibility that a few times the foreach will beat the for loop)  but when you run it a few hundred times you will come to the very conclusion that by average the for loop is remarkable faster than the foreach loop.

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ConsAppForForEach
{
internal class Program
{
private const int MAX_ITERATIONS = 1000000;
private const int MAX_RUNS = 150;

private static void Main(string[] args)
{
List<Int32> Count = new List<int>();
long avgTicksFor = 0;
long avgTicksForEach = 0;

for (int i = 0; i < MAX_ITERATIONS; i++)
{
Count.Add(i);
}

for (int cnt = 0; cnt < MAX_RUNS; cnt++)
{
List<Int32> lst1 = new List<Int32>();
List<Int32> lst2 = new List<Int32>();

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < Count.Count; i++)
{
lst1.Add(i);
}
sw.Stop();
avgTicksFor += sw.ElapsedTicks;

Console.WriteLine("For Loop : " + sw.ElapsedTicks);
sw.Restart();

foreach (int a in Count)
{
lst2.Add(a);
}
sw.Stop();
avgTicksForEach += sw.ElapsedTicks;

Console.WriteLine("ForEach Loop: " + sw.ElapsedTicks);
}
Console.WriteLine("=======================================");
Console.WriteLine("AVG For Loop : " + avgTicksFor / MAX_RUNS);
Console.WriteLine("AVG ForEach Loop : " + avgTicksForEach / MAX_RUNS);
Console.ReadLine();
}
}
}