为什么名单< T> .ForEach比标准的foreach快?名单、标准、LT、GT

2023-09-03 04:24:00 作者:噬梦罪犯

考虑一下:

必要的:

//The alphabet from a-z
List<char> letterRange = Enumerable.Range('a', 'z' - 'a' + 1)
.Select(i => (Char)i).ToList(); //97 - 122 + 1 = 26 letters/iterations

标准的foreach:

Standard foreach:

foreach (var range in letterRange)
{
    Console.Write(range + ",");
}
Console.Write("\n");

内置的foreach:

Inbuilt foreach:

letterRange.ForEach(range => Console.Write(range + ",")); //delegate(char range) works as well
Console.Write("\n");

我已经试过定时对立起来,并在内置的foreach是高达2倍的速度,这似乎想了很多。

I have tried timing them against each other and the inbuilt foreach is up to 2 times faster, which seems like a lot.

我用Google搜索周围,但我似乎无法找到任何答案。

I have googled around, but I can not seem to find any answers.

此外,关于:http://stackoverflow.com/questions/365615/in-c-net-which-loop-runs-faster-for-or-foreach

for (int i = 0; i < letterRange.Count; i++)
{
    Console.Write(letterRange[i] + ",");
}
Console.Write("\n");

不采取行动执行比标准的foreach快,据我可以告诉。

Doesn't act execute faster than standard foreach as far as I can tell.

推荐答案

我想你的基准是有缺陷的。 Console.Write 是I / O密集​​型任务,它是最耗费时间的基准的一部分。这是一种微基准,应为准确的结果非常仔细地进行。

I think your benchmark is flawed. Console.Write is an I/O bound task and it's the most time consuming part of your benchmark. This is a micro-benchmark and should be done very carefully for accurate results.

下面是一个标杆: http://diditwith.net /PermaLink,guid,506c0888-8c5f-40e5-9d39-a09e2ebf3a55.aspx (它看起来不错,但我还没有证实它自己)。 的链接似乎被打破,作为2015年8月14号

Here is a benchmark: http://diditwith.net/PermaLink,guid,506c0888-8c5f-40e5-9d39-a09e2ebf3a55.aspx (It looks good but I haven't validated it myself). The link appears to be broken as of 8/14/2015