First of all, compiling EF queries has nothing to do with performance benefits that can be achieved by using stored procedures.
According to http://msdn.microsoft.com/en-us/library/cc853327.aspx - the following operations occur when a query executes against a conceptual model:
- Loading metadata
- Opening the database connection
- Generating views
- Preparing the query
- Executing the query
- Loading and validating types
- Tracking
- Materializing the objects
And the explanation regarding Preparing the query
:
Includes the costs to compose the query command, generate a command tree based on model and mapping metadata, and define the shape of the returned data. Because Entity SQL query commands are cached, later executions of the same query take even less time. You can also use compiled LINQ queries to reduce this cost in later executions.
So, if you compile the query and re-use it later, what happens is that you save time on this operation in your application during every subsequent query execution. What you don't do, however, is you don't influence the generated SQL code that is executed against the database. The performance benefits you get when compiling queries are at the application level.
On the other hand, you would typically use stored procedures in case you aren't satisfied with the generated SQL code and would like to optimize performance at the database level.
EDIT in response to your comment and edit.
It seems to me that you are under the impression that compiling an EF query would somehow change the generated SQL code that will be run against the database (you mention that compiled queries result in parametrized SQL queries?). That is not the case. No matter whether you run the query directly or use compiledQuery.Invoke
, the same SQL code will be run against the DB. Furthermore, you don't have full control over it, you rather rely on the ORM to generate it in the best possible way. In some cases it is not optimal, and this is where SP's come in.
So to sum up:
- Compiling queries is purely an
application-side optimization. It
saves the time to compile a query
that gets re-used in the code.
- Stored procedures can be used to tweak your SQL code and get it to match your goal as closely as possible, thus providing a possibility to get the best performance at the database level.
In no way is one technique a substitute for the other.