Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can LINQ operations be faster than a normal loop?
    primarykey
    data
    text
    <p>A friend and I were a bit perplexed during a programming discussion today. As an example, we created a fictive problem of having a <code>List&lt;int&gt;</code> of n random integers (typically 1.000.000) and wanted to create a function that returned the set of all integers that there were more than one of. Pretty straightforward stuff. We created one LINQ statement to solve this problem, and a plain insertion sort based algorithm.</p> <p>Now, as we tested the speed the code ran at (using <code>System.Diagnostics.StopWatch</code>), the results were confusing. Not only did the LINQ code outperform the simple sort, but it ran faster than <em>a single</em> <code>foreach</code>/<code>for</code> that only did a single loop of the list, and that had no operations within (which, on a side track, I thought the compiler was supposed to discover and remove alltogether).</p> <p>If we generated a new <code>List&lt;int&gt;</code> of random numbers in the same execution of the program and ran the LINQ code again, the performance would increase by orders of magnitude (typically thousandfold). The performance of the empty loops were of course the same.</p> <p>So, what is going on here? Is LINQ using parallelism to outperform normal loops? How are these results even possible? LINQ uses quicksort which runs at n*log(n), which per definition is already slower than n.</p> <p>And what is happening at the performance leap on the second run?</p> <p>We were both baffled and intrigued at these results and were hoping for some clarifying insights from the community, just to satisfy our own curiosity.</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.
 

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