LINQ Lambda | Query Syntax VS Method Syntax Performance

Asked

Viewed 146 times

5

Doubt regarding the construction and performance of querys using Query Syntax and Method Syntax / LINQ

Query Syntax:

var VendorQuery = from v in vendors
                  where v.CompanyName.Contains("Toy")
                  orderby v.CompanyName
                  select v;

Method Syntax

var vendorQuery = vendors
                  .Where(v => v.CompanyName.Contains("Toy"))
                  .OrderBy(v => v.CompanyName);

Obs: As querys above are fictitious, just to illustrate.

  1. In both situations the same query is mounted?
  2. Assuming I have to do a relatively "heavy" search, it does difference use one or the other?
  • 1

    As far as I know yes, in both scenarios the result is the same. Regarding the "heavy" query, it depends, weighed in record numbers or with many JOIN or GROUP BY?

1 answer

5


Yes it is the same performance for your example. And according to the documentation:

Most queries in the LINQ introductory documentation (Consultation Language integrated) is written using query syntax LINQ declarative. However, the query syntax must be converted into CLR (Common Language Runtime) method calls . NET when the code is compiled.

Taking into account the above specified in the same one that you will use as long as the logic is the same.

To know about performance you have to check the query generated. A tip for you to be able to observe the query generated is to do the following in your Context:

public DatabaseContext() : base("MeuContext")
{
    //Trecho abaixo utilizado para ver as querys geradas pelo Entity
    #if DEBUG
    Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
    #endif
}

That stretch System.Diagnostics.Debug.WriteLine(s) will cause the query generated appears in Output when you are debugging and will help you better understand the generation of querys. You can even test the example you gave here in the question to see if it actually generates the same query.

Reference:

https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq

Browser other questions tagged

You are not signed in. Login or sign up in order to post.