很多时候,我们在选择循环的时候,会考虑用那个循环好一点,这个好一点就是指效果高一点!今天我对于for, foreach循环做了个性能测试,测试代码如下:
// Performance test of for loop.
private void ForLoopPerformance()
{
System.Diagnostics.Debug.WriteLine("ForLoopPerformance: ");
string[] array = new string[10000000];
DateTime d1 = DateTime.Now;
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
System.Diagnostics.Debug.WriteLine(DateTime.Now.Ticks - d1.Ticks);
DateTime d2 = DateTime.Now;
int len = array.Length;
for (int i = 0; i < len; i++)
{
Console.Write(array[i]);
}
System.Diagnostics.Debug.WriteLine(DateTime.Now.Ticks - d2.Ticks);
DateTime d3 = DateTime.Now;
foreach (string str in array)
{
Console.Write(str);
}
System.Diagnostics.Debug.WriteLine(DateTime.Now.Ticks - d3.Ticks);
}
运行结果如下(每次运行结果会有差异):
ForLoopPerformance:
2904263 // for
2804116 // for
2703969 // foreach
结论:
foreach性能最好,其次就是第二个for循环,因为相对于第一个来说,第二个for循环只要进行一个array.GetLength来获取数组的最大下标!
当然了,这个结论也不是绝对的,在选择for, foreach的时候,应该考虑以下几点:
1. 如果只是读数据,优先选择foreach,因为效率高,而且代码简单,方便;
2. 如果要写数据,就只能选择for了,而且选择第二个for效率更高!