It is clear that using
lazy can allow the Swift compiler to more aggressively optimize operations like
filter, especially when those operations are expensive or unnecessary.
What is less clear is whether
lazy can have negative effects on performance or memory usage (putting aside operations that outright break). The documentation of
LazySequenceProtocol includes the following sentence.
When you use the
lazyproperty, you give the standard library explicit permission to store the closure and the sequence in the result, and defer computation until it is needed.
This implies that the compiler will perform either lazy or eager evaluation depending on which is more optimal. If that’s the case, everything should be marked
lazy unless it must be evaluated eagerly to work, as that gives the compiler more freedom for optimization.
If, on the other hand, lazy sequences are always evaluated lazily, then users must consider whether the increased overhead is justified.