在这个线程中,我们讨论了for loop
和的性能分析foreach
。哪一个提供更好的性能- for
or foreach
?
这里有两个简单的方法:
public static void TestFor()
{
Stopwatch stopwatch = Stopwatch.StartNew();
int[] myInterger = new int[1];
int total = 0;
for (int i = 0; i < myInterger.Length; i++)
{
total += myInterger[i];
}
stopwatch.Stop();
Console.WriteLine("for loop Time Elapsed={0}", stopwatch.Elapsed);
}
public static void TestForeach()
{
Stopwatch stopwatchForeach = Stopwatch.StartNew();
int[] myInterger1 = new int[1];
int totall = 0;
foreach (int i in myInterger1)
{
totall += i;
}
stopwatchForeach.Stop();
Console.WriteLine("foreach loop Time Elapsed={0}", stopwatchForeach.Elapsed);
}
然后我运行上面的代码,结果是 foreach 循环 Time Elapsed=00:00:00.0000003,for loop Time Elapsed= 00:00:00.0001462。我认为我们需要高性能代码。我们将使用 foreach