Advertisement
Advanced C#, Collections

How does the 'yield return'-based lazy evaluation of collections (like LINQ or a custom iterator) differ from eagerly materializing a full collection, in terms of memory usage?

Short answer

A lazily-evaluated sequence (built with yield return, or LINQ methods before .ToList()/.ToArray()) computes and holds only ONE element in memory at a time as it's consumed, whereas an eagerly-materialized collection allocates memory for the ENTIRE result set upfront — critical…

Save C# mock interview
Advertisement
AModel answer
A lazily-evaluated sequence (built with yield return, or LINQ methods before .ToList()/.ToArray()) computes and holds only ONE element in memory at a time as it's consumed, whereas an eagerly-materialized collection allocates memory for the ENTIRE result set upfront — critical for processing very large or even infinite sequences without exhausting memory.
IEnumerable<int> LazyRange(int start, int count) {
  for (int i = 0; i < count; i++) yield return start + i; // computed one at a time
}
var firstFew = LazyRange(1, 1_000_000_000).Take(5).ToList(); // only 5 values ever actually computed
Real-world example
Processing an enormous or effectively infinite sequence (like reading lines from a huge file) while only holding a small working set in memory.
Likely follow-ups
  • What happens to this memory advantage if you accidentally call .ToList() too early in a LINQ chain over a lazy sequence?
Related topics