I am running a simple test on loops to see which is inherently faster because my project will be looping over millions of objects. This test fills a List with 1 millions objects, each having a MyClass.Age property. I loop through each objects and pull out the Age property. I do this in a Foreach loop and a For loop. Can someone please explain the weird results OR show me that I've made a stupid error... Thanks
static int trial = 1;
static void Main(string[] args)
{
while (Console.ReadKey().Key == ConsoleKey.Enter)
{
Run();
trial++;
}
}
private static void Run()
{
Console.WriteLine();
Console.WriteLine("Trial " + trial.ToString());
List<MyClass> classes = new List<MyClass>();
for (int x = 1; x <= 1000000; x++)
{
classes.Add(new MyClass(x));
}
DateTime startTime = new DateTime();
DateTime endTime = new DateTime();
DateTime startTime2 = new DateTime();
DateTime endTime2 = new DateTime();
startTime = DateTime.Now;
foreach (MyClass c in classes)
{
int age = c.Age;
}
endTime = DateTime.Now;
TimeSpan span = endTime - startTime;
Console.WriteLine("ForEach Time: " + span.TotalMilliseconds.ToString("#,##0.00000").PadLeft(10) + "ms");
startTime2 = DateTime.Now;
for (int x = 0; x < classes.Count; x++)
{
int age = classes[x].Age;
}
endTime2 = DateTime.Now;
TimeSpan span2 = endTime2 - startTime2;
Console.WriteLine("ForLoop Time: " + span2.TotalMilliseconds.ToString("#,##0.00000").PadLeft(10) + "ms");
}
class MyClass
{
public int Age;
public MyClass(int a)
{
Age = a;
}
}
Results:
Trial 1
ForEach Time: 15.60000ms
ForLoop Time: 0.00000ms
Trial 2
ForEach Time: 0.00000ms
ForLoop Time: 15.60000ms
Trial 3
ForEach Time: 15.60000ms
ForLoop Time: 0.00000ms
Trial 4
ForEach Time: 15.60000ms
ForLoop Time: 0.00000ms
Trial 5
ForEach Time: 15.60010ms
ForLoop Time: 0.00000ms
Trial 6
ForEach Time: 0.00000ms
ForLoop Time: 0.00000ms
Trial 7
ForEach Time: 15.60000ms
ForLoop Time: 0.00000ms
Trial 8
ForEach Time: 15.60010ms
ForLoop Time: 0.00000ms
Trial 9
ForEach Time: 0.00000ms
ForLoop Time: 15.60010ms
Trial 10
ForEach Time: 0.00000ms
ForLoop Time: 0.00000ms