Created
August 21, 2013 13:46
-
-
Save anonymous/6294647 to your computer and use it in GitHub Desktop.
Linqpad microbenchmark of Foreach vs Select.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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