Compiling LINQ Queries

The performance of LINQ queries can suffer greatly when an application performs the same query multiple times with different parameters. A good example of this situation occurs when your query is inside of a loop as shown below:

foreach (Company company in CompanyList)
{
     var customers = (from c in context.Customers
               where c.CompanyID == company.ID
               select c); 

     Console.WriteLine(customers.Count);
}

Each iteration of the above loop requires that the query be translated into SQL. This process becomes increasingly costly based on the number of iterations and the complexity of the query.

To increase the performance, .NET’s LINQ implementation allows us to preform compiled queries. Compiled queries require the use of a Generic Function whose implementation contains the LINQ query to execute.

private static Func<DBDataContext, Guid, Customer>
     GetCustomers = CompiledQuery.Compile(
     (DBDataContext context, Guid companyID) =>
               from c in context.Customers
               where c.CompanyID== companyID
               select c);

This function will compile the LINQ query only once. Subsequent calls to the function will reuse the existing compiled query. This greatly increases the performance of subsequent queries and avoids excessive recompilation. You can call the procedure using a standard function call:

foreach (Company company in CompanyList)
{
     var customers = GetCustomers(context, company.ID); 

     Console.WriteLine(customers.Count);
}

For more information: http://msdn.microsoft.com/en-us/library/bb399335.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*