Lazy evaluation always consumes stack to allocate the metadata, the pointer to the expression. The expression evaluated may also be stored on stack if the expression is simple and no reference type (for example, usage of string or having a value captured in WeakReference
) is used.
We must consider these scenarios:
Always use lazy evaluation whenever possible when doing operations on collections, especially when using a collection that only does forward-only features such as
Sequence
orIEnumerable
, includingIEnumerable<T>
as well.For more complex recursive expressions or computation, lazy evaluation will consume stack rapidly, especially when combining complex lazy evaluation within recursive functions. Eager evaluation is preferred for this scenario, as the result of recursive functions always stored on stack as a stack frame with the last pointer of the previous same function call. If the lazy operation inside a recursive...