我在循环上运行一个简单的测试,看看哪个本身更快,因为我的项目将循环数百万个对象。此测试使用1百万个对象填充List,每个对象都具有MyClass.Age属性。我循环遍历每个对象并拉出Age属性。我在Foreach循环和For循环中执行此操作。有人可以解释一下奇怪的结果,或者告诉我,我犯了一个愚蠢的错误......谢谢
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;
}
}
结果:
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