Search code examples
linqc#-4.0lambdaparallel-processingparallel-extensions

Are lambda faster than linq queries?


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.