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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With