"foreach" VS "List <T> .Foreach" ... which wins
TL DR: the difference in performance here is practically small in a real application, and in any case there is a more readable way to achieve the same result. I'm still interested in seeing the differences in the compiled code.
Assuming the complete 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 will be simpler in terms of what is generated - you will get only a local variable, code to iterate through 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 , as well as a method that will be used as a 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); In addition, there are philosophical differences between foreach and foreach , which Eric Lippert wrote about.
Personally, I would just use LINQ:
int result = intList.Sum(); I doubt that performance differences will actually be a bottleneck in real code, but the LINQ version is the clearest IMO, and this is always good.