LINQ Interview Question #79
What is the difference between deferred execution and lazy evaluation?
Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate
Quick Interview Answer
Deferred execution means execution is postponed until the result is needed. Lazy evaluation is closely related but emphasizes producing values only as they are requested.
Detailed Explanation
Deferred execution means execution is postponed until the result is needed. Lazy evaluation is closely related but emphasizes producing values only as they are requested.
Many LINQ-to-Objects operators are both deferred and lazy. However, some deferred operators such as OrderBy cannot return the first sorted item until they have examined and buffered the source.
Code Example
var result = numbers
.Where(n => n % 2 == 0)
.Select(n => n * 10);
foreach (var item in result)
{
// Items are produced as enumeration proceeds.
Console.WriteLine(item);
}