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);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
vs
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:On top of that there’s the philosophical differences between
foreachandForEachwhich Eric Lippert has written about.Personally I’d just use LINQ though:
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.