Coding Tips & Tricks


Home > LINQ

Compiling LINQ queries for improved performance

I've been using Linq to Sql for quite a while now, and here and there I have heard of compiling your Linq queries mentioned. Now I know that this feature has been around for a while in terms of .net, but I have never actually got round to using it. I started to look into it and found out that it is actually really easy, and it really does improve the performance of your query.

So this is how you would write a standard linq query:

But if we wanted to compile it, we need to write it slightly differently. First we start off with a func :

And then if we need to call this, we simply do the following:

The magic is all in the CompiledQuery.Compile() !

Things to consider

You may not benefit from precompiling your queries in all circumstances. Bear in mind that a compiled query needs to be run more than once for the compilation and caching to be truly effective. In some circumstances, if you are using a complex query, precompiling might add a little overhead. Overall though, I would definitely still recommend that you compile your LINQ queries to improve your performance. You will definitely notice the results!

Here are some links I came across whilst researching this topic:-

Some more information about the positives and negatives of precompiling LINQ queries - http://msdn.microsoft.com/en-us/magazine/ee336024.aspx

From the MSDN site:- http://msdn.microsoft.com/en-us/library/bb399335.aspx








Comments

Tim Acheson - 6/28/2010
Surprisingly easy! A nice, simple performance boost. Nice article. Thanks!


Add your comment

300 Characters left


Please fill this in to confirm that you are human