Why are LINQ operations faster than a regular loop?

A friend and I were a bit puzzled during the discussion of programming today. As an example, we created a fictitious problem of having List<int>n random integers (usually 1.000.000) and wanted to create a function that returned the set of all integers, the number of which was more than one. Pretty simple stuff. We created one LINQ statement to solve this problem and a simple insertion sorting algorithm.

Now that we have tested the speed at which the code worked (using System.Diagnostics.StopWatch), the results were confusing. Not only did LINQ code outperform the simple view, but it worked faster than one foreach/ for, which only performed one list loop and had no operations inside (which on the side track I thought the compiler should have detected and deleted all together).

If we generated a new List<int>random number in the same program execution and ran LINQ code again, the performance would increase by orders of magnitude (usually a thousand times). The performance of the empty loops was, of course, the same.

So what is going on here? Is LINQ used with parallelism to outperform regular loops? How are these results possible? LINQ uses quicksort, which runs in n * log (n), which by definition is already slower than n.

And what happens when the performance jump in the second run?

We were both puzzled and intrigued by these results, and hoped for some clarifying ideas from the community, just to satisfy our own curiosity.

+5
source share
3 answers

, , . LINQ , , , . ToList() Count() LINQ, .

, , , . . , ; - , , .

var dataset = ...

var watch = Stopwatch.StartNew();

var query = dataset.Where( d => dataset.Count( i => i == d ) > 1 );

watch.Stop();  // timer stops here

foreach (var item in query) // query is actually evaluated here
{
   ... print out the item...
}
+13

, LINQ , " ", ( ). LINQ , , ..

LINQ " " " " ( ) //. - .

, , - . , , , LINQ .

+1

" ", , , . (, , , .)

However, the code underlying LINQ is part of an already compiled code that would certainly be optimized (using JIT, NGen, or similar).

+1
source

All Articles