Linq Compiled Queries Q & A

I did a series of postings on Linq Compiled Queries last year, I recently got some questions on those postings that I thought would be of general interest.


Why use the 'new' keyword in this snippet?

var q = from o in nw.Orders
select new {o.everything …};


If you did just :

var q = from o in nw.Orders
select o;

You're getting editable orders. Linq then has to track them in case you change them and want to submit the changes. If you use new effectively you're making a copy of the orders that is not going to be change tracked. That's faster for read only cases. The other thing you can do is mark the query context as read-only and then you get the same effect.  When I wrote that test case, that feature wasn't available yet so I used new to simulate it.


What do you mean when you say that linq will 'Create custom methods that bind the data perfectly' ?


Whenever you use linq to sql to read data from a database it has to do two important things for you. The first is convert your Linq query into SQL. The second is to make a method that takes the stream of data that comes back from the database and converts it into the managed objects you required. That's the data-binding step. Linq creates the necessary methods automatically, and it makes the perfect code for doing this.


How did Linq to SQL beat your ADO.Net code for insert times.  Shouldn't a tie be the best possible result?


The SQL I used in my test case was pretty much the standard simplest SQL you would use for such a job. The automatically generated SQL from Linq was better than what I wrote by hand because they had parameterized the insert statements which I never bothered to do. Had I changed my SQL to what they created it would have been a tie. This is kind of like when the C++ compiler finds a machine code pattern that is better than what you would have written doing it by hand because it did something you don't usually bother doing with hand tuned machine code. But you *could* replace what you wrote with what the compiler generated.


What are the downsides to precompiled queries?


There is no penalty to precompiling (see Quiz #13). The only way you might lose performance is if you precompile a zillion queries and then hardly use them at all -- you'd be wasting a lot of memory for no good reason. 

But measure :)