I was looking through the sample LINQ queries provided with LINQPad taken from the C# 4.0 in a Nutshell book, and ran across something I have never used in LINQ to SQL... Compiled Queries.
Here is the exact exmaple:
// LINQ to SQL lets you precompile queries so that you pay the cost of translating
// the query from LINQ into SQL only once. In LINQPad the typed DataContext is
// called TypeDataContext, so we proceed as follows:
var cc = CompiledQuery.Compile ((TypedDataContext dc, decimal minPrice) =>
from c in Customers
where c.Purchases.Any (p => p.Price > minPrice)
select c
);
cc (this, 100).Dump ("Customers who spend more than $100");
cc (this, 1000).Dump ("Customers who spend more than $1000");
What does precompiling a LINQ to SQL query like this actually buy me? Would I get a performance boost from a query slightly more complex than this one? Is this even used in actual practice?
The way I use compiled queries is in a static way: I statically declare the compiled query, so the query tree structure has to be parsed only once, and you basically have a prepared statement that just needs some extra parameters. This is mainly used on websites, so the query has to be compiled only once, ever. The performance gain depends of course on the complexity of your query.
We use this at our company and for queries that are run often need not be compiled for each run. You don't have to get overly complex with linq to sql before this makes a difference, but that will depend on the traffic and load on the servers.
In a nutshell, precompiled querires buy you a performance gain when you need to run a single query multiple times.
Here's some information on LINQ To SQL performance.
From this article from Rico Mariani's Performance Tidbits