Lazy evaluation of closures


#1

Hello,

In my crate there is some validation code similar to this example. I would like to make the evaluation of path lazy, that is, to ensure path is only constructed when an error actually occurs and not during every call to validate().

In the implemenation of Validate::lazy in the example, is it guaranteed that path will in fact be lazily evaluated as described?

The actual validation code I’m referring to is sitting here but uses the eager version from the example.


#2

Yes, it’ll be lazy. Specifically, the body of the lambda will run lazily; the creation of a struct that the compiler generates to desugar the lambda is eager.


#3

Thanks for your reply; that answers my question.

My only remaining concern is whether it’s cheaper to create these compiler generated structs than it is to create the strings. That’s something for me to investigate, I guess.


#4

It’s almost surely cheaper, as the struct will be created directly without any heap allocation.


#5

As @cuviper mentioned, it’ll be cheaper both in terms of CPU cycles and also heap allocator pressure (since it’ll be on the stack). Moreover, the compiler may inline through your entire call chain and then flat out remove the struct allocation altogether, and just replace its uses with the scalar values directly.


#6

Great, that’s exactly what I wanted to hear. Thanks for clarifying.