Are lambda faster than linq queries?
-
08-07-2021 - |
Question
Iam playing with lambda, linq and parallel and one question arrives.
Is lambda faster than linq queries?
O write some test code (Fork it in GitHub) and the lambda method seems faster. It is true or i am missing something?
Solution
Your queries aren't the same.
Query expression:
from p in lista
where p.Age > 18 && p.Age < 60 && p.Phone.StartsWith("11")
select p
Regular extension method calls:
.Where(n => n.Age > 18).
Where(n => n.Age < 60).
Where(n => n.Phone.StartsWith("11"))
The first one calls Where
once; the second calls Where
three times. To make them behave exactly the same you should use:
.Where(n => n.Age > 18 && n.Age < 60 && n.Phone.StartsWith("11"))
At that point, the two forms will compile to exactly the same code.
Additionally, there's a huge hole in your testing: you're testing building the query... you're never actually evaluating it:
sw.Start();
IEnumerable listaSemParalelismoLinq = from p in lista
where p.Age > 18 && p.Age < 60 &&
p.Phone.StartsWith("11")
select p;
sw.Stop();
You must use the query in some form, e.g. calling Count()
on it, in order to make it actually "execute". (You'll need to change the type to the generic IEnumerable
form, e.g. using var
.) The time taken to simply construct the query is basically irrelevant in almost all cases.
OTHER TIPS
I do the modifications sugested by @Jon Skeet, run the program in the following order
Console.WriteLine("1 - LINQ without paralelism " + LinqWithoutParalelism(lista));
Console.WriteLine("2 - LINQ with paralelism " + LinqWithParalelism(lista));
Console.WriteLine("3 - Lambda without paralelism: " + LambdaWithoutParalelism(lista));
Console.WriteLine("4 - Lambda with paralelism: " + LambdaWithParalelism(lista));
And aparently the lamba is faster, but i change the order of the execution to
Console.WriteLine("3 - Lambda without paralelism: " + LambdaWithoutParalelism(lista));
Console.WriteLine("4 - Lambda with paralelism: " + LambdaWithParalelism(lista));
Console.WriteLine("1 - LINQ without paralelism " + LinqWithoutParalelism(lista));
Console.WriteLine("2 - LINQ with paralelism " + LinqWithParalelism(lista));
and the lambda is not the faster one. I know this test is very simple and i am not considering the warmup time and to do a lot of interactions, but, ACTUALY my answer is: NO, lambda arent faster than linq queries.