LINQ Interview Question #92
Why can calling ToList too early hurt performance?
Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate
Quick Interview Answer
Early materialization can retrieve more rows or columns than the application needs and forces later filtering or projection to happen in memory. This can increase database work, network traffic, application memory usage, and response time.
Detailed Explanation
Early materialization can retrieve more rows or columns than the application needs and forces later filtering or projection to happen in memory. This can increase database work, network traffic, application memory usage, and response time.
For database queries, compose translatable filters, projections, ordering, and pagination before materialization whenever practical.
Code Example
// Better:
var names = await db.Products
.Where(p => p.IsActive)
.OrderBy(p => p.Name)
.Select(p => p.Name)
.Take(50)
.ToListAsync();