foreach (var item in items) {} using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace ArrayTest { public class Foo { public string Bar1 { get; set; } public string Bar2 { get; set; } public string Bar3 { get; set; } public string Bar4 { get; set; } public string Bar5 { get; set; } } class Program { const int Size = 10000000; static readonly List Output = new List(); static readonly List Print = new List(); static void Main() { var foo1 = GetFoo1(); var foo2 = GetFoo2(); UseArray(foo1); UseIEnumerable(foo2); // Get random element from the list. Just for avoiding compiler optimization. int i = new Random().Next(Output.Count); Console.WriteLine(Output[i]); foreach (string o in Print) { Console.WriteLine(o); } } private static void WriteLine(string x) { Output.Add(x); } private static Foo[] GetFoo1() { Stopwatch sw = Stopwatch.StartNew(); var foo1 = new Foo[Size]; for (int i = 0; i < Size; i += 1) { var foo = new Foo { Bar1 = "Bar1", Bar2 = "Bar2", Bar3 = "Bar3", Bar4 = "Bar4", Bar5 = "Bar5" }; foo1[i] = foo; } sw.Stop(); Print.Add(string.Format("CreateArray: {0}", sw.ElapsedMilliseconds)); return foo1; } private static IEnumerable GetFoo2() { Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < Size; i += 1) { var foo = new Foo {Bar1 = "Bar1", Bar2 = "Bar2", Bar3 = "Bar3", Bar4 = "Bar4", Bar5 = "Bar5"}; yield return foo; } sw.Stop(); Print.Add(string.Format("CreateIEnumerable: {0}", sw.ElapsedMilliseconds)); } static void UseArray(T[] values) { Stopwatch sw = Stopwatch.StartNew(); var count = values.Length; foreach (object o in values) { var x = (Foo)o; WriteLine(x.Bar1); } sw.Stop(); Print.Add(string.Format("UseArray: {0}, count: {1}", sw.ElapsedMilliseconds, count)); } static void UseIEnumerable(IEnumerable values) { Stopwatch sw = Stopwatch.StartNew(); var count = values.Count(); foreach (object o in values) { var x = (Foo)o; WriteLine(x.Bar1); } sw.Stop(); Print.Add(string.Format("UseIEnumerable: {0}, count: {1}", sw.ElapsedMilliseconds, count)); } } }