1
我正在循環中運行一個簡單的測試,以查看哪個固有更快,因爲我的項目將循環超過數百萬個對象。此測試用1百萬個對象填充List,每個對象都有一個MyClass.Age屬性。我遍歷每個對象並提取Age屬性。我在Foreach循環和For循環中執行此操作。有人可以解釋的怪異的結果,或者告訴我,我犯了一個愚蠢的錯誤...感謝Foreach vs 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
修正了它。你介意爲什麼Datetime.Now這樣行事嗎? – user2777664
@ user2777664,是的。檢查這篇文章http://stackoverflow.com/questions/2923283/stopwatch-vs-using-system-datetime-now-for-timing-events(或)MSDN文檔。簡而言之,'stopwatch'比'DateTime.Now'提供更高的精度。 – Rahul
謝謝!我很感激。 – user2777664