Skip to content

Instantly share code, notes, and snippets.

@wiennat
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save wiennat/10731478 to your computer and use it in GitHub Desktop.

Select an option

Save wiennat/10731478 to your computer and use it in GitHub Desktop.
Comparison between foreach and while over IEnumerable
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ForEachWhile
{
class Program
{
static IEnumerable<int> Foo(int n)
{
for (int i = 0; i < n; i++)
{
yield return i;
}
}
static void Main(string[] args)
{
IEnumerable<int> testForEach = Foo(10000000);
IEnumerable<int> testWhile = Foo(10000000);
IEnumerator<int> iterator = testWhile.GetEnumerator();
Stopwatch sw = new Stopwatch();
sw.Start();
foreach (var item in testForEach)
{
}
sw.Stop();
Console.WriteLine("foreach " + sw.ElapsedTicks);
sw.Restart();
while (iterator.MoveNext())
{
int item = iterator.Current;
}
sw.Stop();
Console.WriteLine("while " + sw.ElapsedTicks);
}
}
}
foreach while
297842 277067
297586 278804
299227 278911
298107 276781
298082 278367
297696 277470
297788 277902
299118 278959
295432 276546
297956 278808
avg ticks
foreach: 297883
while: 277962
median
foreach: 297899
while: 278136
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment