Note that there are some explanatory texts on larger screens.

plurals
  1. POOrder of LINQ extension methods does not affect performance?
    primarykey
    data
    text
    <p>I'm surprised that it apparently doesn't matter whether i prepend or append LINQ extension methods. </p> <p>Tested with <a href="http://msdn.microsoft.com/en-us/library/bb340482.aspx"><code>Enumerable.FirstOrDefault</code></a>:</p> <ol> <li><code>hugeList.Where(x =&gt; x.Text.Contains("10000")).FirstOrDefault();</code></li> <li><p><code>hugeList.FirstOrDefault(x =&gt; x.Text.Contains("10000"));</code></p> <pre><code>var hugeList = Enumerable.Range(1, 50000000) .Select(i =&gt; new { ID = i, Text = "Item" + i }); var sw1 = new System.Diagnostics.Stopwatch(); var sw2 = new System.Diagnostics.Stopwatch(); sw1.Start(); for(int i=0;i&lt;1000;i++) hugeList.Where(x =&gt; x.Text.Contains("10000")).FirstOrDefault(); sw1.Stop(); sw2.Start(); for(int i=0;i&lt;1000;i++) hugeList.FirstOrDefault(x =&gt; x.Text.Contains("10000")); sw2.Stop(); var result1 = String.Format("FirstOrDefault after: {0} FirstOrDefault before: {1}", sw1.Elapsed, sw2.Elapsed); //result1: FirstOrDefault after: 00:00:03.3169683 FirstOrDefault before: 00:00:03.0463219 sw2.Restart(); for (int i = 0; i &lt; 1000; i++) hugeList.FirstOrDefault(x =&gt; x.Text.Contains("10000")); sw2.Stop(); sw1.Restart(); for (int i = 0; i &lt; 1000; i++) hugeList.Where(x =&gt; x.Text.Contains("10000")).FirstOrDefault(); sw1.Stop(); var result2 = String.Format("FirstOrDefault before: {0} FirstOrDefault after: {1}", sw2.Elapsed, sw1.Elapsed); //result2: FirstOrDefault before: 00:00:03.6833079 FirstOrDefault after: 00:00:03.1675611 //average after:3.2422647 before: 3.3648149 (all seconds) </code></pre></li> </ol> <p>I would have guessed that it would be slower to prepend <code>Where</code> since it must find all matching items and then take the first and a preceded <code>FirstOrDefault</code> could yield the first found item. </p> <p><strong>Q:</strong> Can somebody explain why i'm on the wrong track? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    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