“foreach”VS“List <t> .Foreach”......获胜</t>

时间:2011-11-09 06:47:58

标签: c# performance generics compiler-construction foreach

谈到更优选使用的性能级别,并且在编译器工作方面更轻,并且有任何重大差异?

  List<int> intList;
  foreach (int i in intList)

intList.ForEach(i => result += i);

3 个答案:

答案 0 :(得分:13)

TL; DR:这里的性能差异几乎肯定在实际应用中无关紧要,并且无论如何都有更可读的方式来实现相同的结果。看到编译代码的差异仍然很有趣。

假设完整代码实际上是:

int result = 0;
foreach (int i in intList)
{
    result += i;
}

VS

int result = 0;
intList.ForEach(i => result += i);

然后第一种形式就生成的内容而言相当简单 - 你最终只会得到一个局部变量,代码迭代列表(使用List<T>.Enumerator)和IL会增加值到本地变量。

第二种形式需要生成一个带有result实例变量的新类,以及一个用作委托的方法。代码将转换为:

CompilerGeneratedClass tmp = new CompilerGeneratedClass();
tmp.result = 0;
Action<int> tmpDelegate = new Action<int>(tmp.CompilerGeneratedMethod);
intList.ForEach(tmpDelegate);

除此之外,foreachForEach Eric Lippert has written about之间存在哲学差异。

就个人而言,我只是使用LINQ:

int result = intList.Sum();

我怀疑性能差异实际是实际代码中的瓶颈,但LINQ版本是最清晰的IMO,并且总是一个好的的事情。

答案 1 :(得分:1)

this benchmark。看来你的例子显示List<int>.ForEach()实际上会更快。

答案 2 :(得分:1)

您可以像这样衡量每个人所需的时间:

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

“你的代码在这里”

stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed.ToString());