4

speaking on performance level which is more preferred to be used and is lighter in terms of compiler work and there any major differences?

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

or

intList.ForEach(i => result += i);
SShebly
  • 2,043
  • 1
  • 21
  • 29
  • 7
    When you measured it what were your results? – Conrad Frix Nov 09 '11 at 06:51
  • Have you tried checking yourself? Do you know how to performance test code? –  Nov 09 '11 at 06:51
  • possible duplicate of [.Net - When is List.ForEach prefered over a standard foreach loop?](http://stackoverflow.com/questions/1172977/net-when-is-listt-foreach-prefered-over-a-standard-foreach-loop) – Ian Mercer Nov 09 '11 at 06:52
  • possible duplicate of [In .NET which loop runs faster for or foreach](http://stackoverflow.com/questions/365615/in-net-which-loop-runs-faster-for-or-foreach) – Amy B Nov 09 '11 at 17:24

1 Answers1

16

TL;DR: The performance difference here is almost certainly insignificant in a real application, and there's a more readable way of achieving the same result anyway. It's still interesting to see the differences in compiled code though.

Assuming the full code is actually:

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

vs

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

then the first form is rather simpler in terms of what gets generated - you'll end up with just a local variable, code to iterate over the list (using List<T>.Enumerator) and IL which adds the value to the local variable.

The second form will need to generate a new class with an instance variable for result, along with a method to be used as the delegate. The code will be converted to:

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

On top of that there's the philosophical differences between foreach and ForEach which Eric Lippert has written about.

Personally I'd just use LINQ though:

int result = intList.Sum();

I doubt that the performance differences will actually be a bottleneck in real code, but the LINQ version is the clearest IMO, and that's always a good thing.

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194