When should I use a CompiledQuery?

Technology CommunityCategory: LINQWhen should I use a CompiledQuery?
VietMX Staff asked 3 years ago

You should use a CompiledQuery when all of the following are true:

  • The query will be executed more than once, varying only by parameter values.
  • The query is complex enough that the cost of expression evaluation and view generation is “significant” (trial and error)
  • You are not using a LINQ feature like IEnumerable<T>.Contains() which won’t work with CompiledQuery.
  • You have already simplified the query, which gives a bigger performance benefit, when possible.
  • You do not intend to further compose the query results (e.g., restrict or project), which has the effect of “decompiling” it.

CompiledQuery does its work the first time a query is executed. It gives no benefit for the first execution. Like any performance tuning, generally avoid it until you’re sure you’re fixing an actual performance hotspot. Note EF 5 will do this automatically.