Skip to content

Instantly share code, notes, and snippets.

Created August 21, 2013 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/6294647 to your computer and use it in GitHub Desktop.
Save anonymous/6294647 to your computer and use it in GitHub Desktop.
Linqpad microbenchmark of Foreach vs Select.
void Main()
{
var fooList = Enumerable.Range(0, 1000).Select( n => new Foo { Bar = "Bar" + n.ToString() } ).ToList();
ForeachTest(fooList);
LinqTest(fooList);
var timer = Stopwatch.StartNew();
for(int i = 0; i < 100000; i++)
{
ForeachTest(fooList);
}
timer.Stop();
var test1 = timer.Elapsed;
timer.Restart();
for(int i = 0; i < 100000; i++)
{
LinqTest(fooList);
}
timer.Stop();
var test2 = timer.Elapsed;
Console.WriteLine("Foreach loop test ran in {0}", test1);
Console.WriteLine("Linq test ran in {0}", test2);
Console.WriteLine("Difference between Foreach and Linq {0}", test2.Subtract(test1));
}
private static void ForeachTest(List<Foo> fooList)
{
var barList = new List<string>(fooList.Count);
foreach(var item in fooList)
{
barList.Add(item.Bar);
}
}
private static void LinqTest(List<Foo> fooList)
{
var barList = fooList.Select(x => x.Bar).ToList();
}
public class Foo
{
public string Bar { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment