foreach 比 for 慢 20 倍?

Elo*_*noa 1 c# performance foreach loops for-loop

迭代没有元素的数组或列表时,foreach 与 for 相比似乎非常慢。运行下面的代码,我得到的结果是:

3ms
143ms
7ms

foreach 真的很慢还是我做错了什么?

var l = new List<int>();
var watch = new Stopwatch();
var test = 0;

watch.Start();
for (int i = 0; i < 10000000; i++) 
    if (l.Count > 0) 
        test = 1;
watch.Stop();
Debug.Log(watch.ElapsedMilliseconds);

watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++) 
    foreach (var item in l) 
        test = 1;
watch.Stop();
Debug.Log(watch.ElapsedMilliseconds);

watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++) 
    for (int j = 0; j < l.Count; j++) 
        test = 1;
watch.Stop();
Debug.Log(watch.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)

Ruf*_*s L 5

循环foreach需要使用 anEnumerator来迭代集合,这需要访问Current属性并调用MoveNext方法,这需要一些处理时间。

\n\n

循环for只需get_Item在每次迭代时调用,因此\xe2\x80\x99s 比foreach循环少一次调用,这在性能上略有不同。

\n