为什么名单< T> .ForEach比标准的foreach快? [英] Why is List<T>.ForEach faster than standard foreach?

查看:144
本文介绍了为什么名单< T> .ForEach比标准的foreach快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

必要的:

//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.

此外,关于:<一href="http://stackoverflow.com/questions/365615/in-c-net-which-loop-runs-faster-for-or-foreach">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

这篇关于为什么名单&LT; T&GT; .ForEach比标准的foreach快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆