LINQ vs Lambda vs loop – A performance test


I was wondering about the benefits of using Linq over Lambda or vice versa for data filtering. I knew that the for loop was the fastest. But I was really interested to know whether lambda expression had any advantage over traditional LINQ syntax.

For my understanding, both LINQ and lambda were same.

Lambdas are the inline method type things that you are passing as a parameter to the Where function in the second example.

The difference between those two syntaxes is purely syntactic. The second linq style using method calls is how it works under the hood. The first is meant to be more user friendly/easier and the compiler converts it to method calls behind the scenes. They should work the same for any given query though of course the compiler may choose a sligthly different interpretation of a complicated linq query than you would when converting to method style.

This msdn article may be of interest too: LINQ Query Syntax versus Method Syntax. Of particular relevance is: “In general, we recommend query syntax because it is usually simpler and more readable; however there is no semantic difference between method syntax and query syntax.”

 

The compiler changes the query expression into the equivalent Lambda expression before compiling it, so the generated IL is exactly the same.

Example:

is exactly the same as

Note that if you write the query expression like this:

It’s converted to:

The final call to Select is omitted because it’s redundant.

I thought of putting this theory into test:

Here’s the output for the same:
LINQ: 00:00:01.7072859, avg. 00:00:00.0004321
LAMBDA: 00:00:02.1314676, avg. 00:00:00.0005394
Loop: 00:00:01.3116814, avg. 00:00:00.0003319

I thought LAMBDA would be equal to LINQ. But that was not the case. I’ll try to find a more practical scenario to test the output. But for now, LINQ seems to be the go between the two!

If you want an amazing article about LINQ, look no further: http://www.codeproject.com/Articles/286255/Using-LINQ-Queries