How to make a Linq to Sql query twice as fast…

An important action with every LinqToSql query is to transform your lambda’s into T-SQL. In simple queries this can take half of the time. By compiling the query you can cache the result of this transformation which saves a lot of processing time on each succeeding query.

There’s a nice write-up over here on how to compile your queries at :http://aspguy.wordpress.com/2008/08/15/speed-up-linq-to-sql-with-compiled-linq-queries/

There’s one tip though I like to mention. If you use simple filter criteria you do not need to create a special SearchCriteria class as mentioned in the post.

var countByCityName = CompiledQuery.Compile(
                        (AdventureWorksDataContext dc, string cityName) =>
                            (from CustomerAddress a in dc.CustomerAddresses
                             where a.Address.City == cityName
                             select a).Count()
                      );

No Comments