C# and Auto-Compiled LINQ Queries

The recently released Microsoft Entity Framework (EF) June 2011 CTP includes support for Auto-Compiled LINQ Queries. This allows every LINQ to Entities query to be automatically executed when compiled and placed in the EF query cache. Every time you run the query subsequently, the EF will find it in its query cache and won’t have to go through the whole compilation process again. This feature also provides a boost to queries issued using WCF Data Services, as it uses LINQ in the background.

How does it Work?

The EF will pass the nodes in the expression tree and create a hash, and become the keys used in the query cache. If it does not find the query in the cache then it will go ahead and compile it and store the compiled query in the cache for subsequent use. Each subsequent time, the hash will be calculated and find the compiled query in the tree, thus saving the compilation overhead.

Which performs faster: when the “Auto-Compiled LINQ Queries” is used or when the CompiledQuery is invoked?

The size and complexity of the application and queries will greatly influence its performance boost. By running a regular query 10 times using auto-compiled mode and 10 times where the compilation is turned off, the total time measured by Visual Studio’s profiling tools for the compiled queries is about 3 times faster than the non-compiled one.

In general, auto-compiled queries are not as fast as invoking a CompiledQuery. What we discussed here is that the new released CTP provides the performance savings for free.

Copyright © All Rights Reserved - C# Learners