原文地址:http://jacksondunstan.com/articles/3165
正文:
foreach循环非常好使,但是for循环更快?这是个简单的问题,但是却在很多代码里有广泛的影响。本文测试了for和foreach,看看用两者遍历一个数组和list到底谁快。
测试很简单,我做了一个object数组,和一个object的System.Collections.Generic.List,它们长度确定,分别使用for和foreach循环遍历。因为循环小于1毫秒,所以每个循环运行100000次。
测试代码:
using System;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour
{
private const int NumIterations = 100000;
private string report;
void Start()
{
report = "Size,Array For Time,Array Foreach Time,List For Time,List Foreach Time\n";
var sizes = new []{10,100,1000};
foreach (var size in sizes)
{
report += Test(size);
}
}
private string Test(int size)
{
var array = new object[size];
var list = new List<object>(size);
list.AddRange(array);
var stopwatch = new System.Diagnostics.Stopwatch();
object obj = null;
stopwatch.Reset();
stopwatch.Start();
for (var iteration = 0; iteration < NumIterations; ++iteration)
{
for (int i = 0, len = array.Length; i < len; ++i)
{
obj = array[i];
}
}
var arrayForTime = stopwatch.ElapsedMilliseconds;
stopwatch.Reset();
stopwatch.Start();
for (var iteration = 0; iteration < NumIterations; ++iteration)
{
foreach (var cur in array)
{
}
}
var arrayForeachTime = stopwatch.ElapsedMilliseconds;
stopwatch.Reset();
stopwatch.Start();
for (var iteration = 0; iteration < NumIterations; ++iteration)
{
for (int i = 0, len = list.Count; i < len; ++i)
{
obj = list[i];
}
}
var listForTime = stopwatch.ElapsedMilliseconds;
stopwatch.Reset();
stopwatch.Start();
for (var iteration = 0; iteration < NumIterations; ++iteration)
{
foreach (var cur in list)
{
}
}
var listForeachTime = stopwatch.ElapsedMilliseconds;
return size + ","
+ arrayForTime + ","
+ arrayForeachTime + ","
+ listForTime + ","
+ listForeachTime + "\n";
}
void OnGUI()
{
GUI.TextArea(new Rect(0, 0, Screen.width, Screen.height), report);
}
}
如果你自己想试试,可以把代码复制到TestScript.cs文件,把这个文件放到Unity的Assets文件夹下,附加到摄像机对象上,然后在64位处理器的non-development模式下构建,并运行在640*480的窗口模式下。
我测试的机器配置:
- 2.3 Ghz Intel Core i7-3615QM •Mac OS X 10.10.4
- Unity 5.1.2f1, Mac
- OS X Standalone, x86_64, non-development
- 640×480, Fastest, Windowed
下面是我得到的测试结果:
size | for遍历数组 | foreach遍历数组 | for遍历list | foreach遍历list |
---|---|---|---|---|
10 | 2 | 1 | 3 | 19 |
100 | 28 | 10 | 35 | 95 |
1000 | 243 | 75 | 343 | 832 |
结论是,对数组来说,foreach比for要快。对于List,for循环比较快。当你循环一个很长的数组或者list的时候得注意点,但是注意这个测试循环了100000次,所以实际差别会小很多。遍历一百万个元素的list大概会花费8毫秒,在这个情况下用for循环会更好的优化,想要继续优化,可以参考这个文章(不安全的代码循环)。
综上所述,for和foreach遍历速度有差别,而且依赖于你要遍历啥。两者速度都很快,在你的app里可能他们的速度差别没那么大。