How does EF Core's compiled queries feature improve performance for frequently-executed queries, and when is it worth using?
Short answer
EF Core normally caches the compiled internal representation of a LINQ query automatically based on its expression tree shape, but EF.CompileAsyncQuery explicitly pre-compiles a parameterized query once, bypassing some per-execution overhead (like expression tree comparison for…
Advertisement
AModel answer
EF Core normally caches the compiled internal representation of a LINQ query automatically based on its expression tree shape, but EF.CompileAsyncQuery explicitly pre-compiles a parameterized query once, bypassing some per-execution overhead (like expression tree comparison for cache lookup) for extremely hot, frequently-repeated queries -- generally only worth the added code complexity for queries executed an enormous number of times (like a high-throughput API's most critical hot path), since EF Core's automatic query caching already handles the vast majority of common scenarios well without manual compilation.
private static readonly Func<AppDbContext, int, Task<Product?>> _getProductById =
EF.CompileAsyncQuery((AppDbContext context, int id) =>
context.Products.FirstOrDefault(p => p.Id == id));
// Usage: skips some per-call query compilation overhead
var product = await _getProductById(context, productId);Real-world example
A payment-processing hot path executed millions of times per day adopts a compiled query for its single most performance-critical lookup after profiling showed measurable query-compilation overhead at that specific extreme scale, while leaving all other, less frequently-hit queries as normal LINQ.
Likely follow-ups
- What specific overhead does EF.CompileAsyncQuery actually eliminate?
- Why isn't compiled queries recommended as a default practice for all queries?
Related topics