.Foreach" ... which wins talking about the level of performance that is more preferable to use and easier in terms of the co...">

"foreach" VS "List <T> .Foreach" ... which wins

talking about the level of performance that is more preferable to use and easier in terms of the compiler, and are there any significant differences?

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

or

 intList.ForEach(i => result += i); 
+4
source share
3 answers

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.

+10
source

see this test . it seems to you that your example that List<int>.ForEach() will actually be consistently faster.

+1
source

You can measure the time it takes for each of them:

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

"Your code is here"

 stopWatch.Stop(); Console.WriteLine(stopWatch.Elapsed.ToString()); 
+1
source

Source: https://habr.com/ru/post/1380339/


All Articles