4 ms·
> that still doesn't explain why there can't There can, you'd have to write it yourself. > If a given lambda can capture via a single frame pointer (because i
by steveklabnik 8y ago
> that still doesn't explain why there can't
There can, you'd have to write it yourself.
> If a given lambda can capture via a single frame pointer (because it borrows everything), why can't that frame pointer just be stored directly in the `data` field?
If there's a single thing it's borrowing, then yes, it could. If there's any more than one, it won't fit.
> Or are you saying that lambdas that borrow everything aren't actually all that common?
I'm saying that closures that borrow exactly one thing aren't actually all that common.
- int_19h 8y agoI think you're misunderstanding what I mean by "frame pointer". What I'm saying is that if a lambda is capturing local variables from a single stack frame by borrow (which ensures that it can't outlive them), then it doesn't need individual pointers to every variable. It just needs a pointer to the stack frame where they live, and it can access the individual variables by offset, same as the function to which that frame belongs does. It's compiler magic, of course - i.e. it means that such lambdas don't have a straightforward translation to a regular Rust object. But it's magic that behaves as if you had individual references, so it's a completely transparent optimization except for size of the resulting object. On Intel architectures, you can think of it as stashing away EBP/RBP. And lambdas that only capture locals from one frame, and all of them by reference, seems like a very common kind of lambda to me, making that optimization worthwhile.
- steveklabnik 8y agoAh! Yes, I see now. I think that D implements closures this way? I thought you meant the closure’s conceptual stack frame. As for commonality, the most common closures I see are: * closures which have no environment * closures that take the environment by move * everything else It’d be interesting to analyze crates.io and see though...and how much this would actually save you. I can't think of a time when the closure is only pointing to its parent's stack frame and you would box it. Box<Fn()> is mostly used for returning closures, and there, you'd be using a move closure to take the env by owner. And even if you do unnecessarily box: https://play.rust-lang.org/?gist=c16ac5983579d52d4997b3f44258748b&version=stable&mode=release&edition=2015 https://play.rust-lang.org/?gist=c16ac5983579d52d4997b3f4425... If you click "show assembly", do_closure_stuff is compiled to: playground::do_closure_stuff: leal 2(%rdi), %eax retq It gets entirely optimized away anyway.