Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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.</p> <p>Assuming the full code is actually:</p> <pre><code>int result = 0; foreach (int i in intList) { result += i; } </code></pre> <p>vs</p> <pre><code>int result = 0; intList.ForEach(i =&gt; result += i); </code></pre> <p>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 <code>List&lt;T&gt;.Enumerator</code>) and IL which adds the value to the local variable.</p> <p>The second form will need to generate a new class with an instance variable for <code>result</code>, along with a method to be used as the delegate. The code will be converted to:</p> <pre><code>CompilerGeneratedClass tmp = new CompilerGeneratedClass(); tmp.result = 0; Action&lt;int&gt; tmpDelegate = new Action&lt;int&gt;(tmp.CompilerGeneratedMethod); intList.ForEach(tmpDelegate); </code></pre> <p>On top of that there's the <em>philosophical</em> differences between <code>foreach</code> and <code>ForEach</code> which <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx">Eric Lippert has written about</a>.</p> <p>Personally I'd just use LINQ though:</p> <pre><code>int result = intList.Sum(); </code></pre> <p>I doubt that the performance differences will <em>actually</em> be a bottleneck in real code, but the LINQ version is the clearest IMO, and that's <em>always</em> a good thing.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload