[Issue 24838] @nogc lambda shouldn't allocate closure when lambda refers only to 'this'
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Mon Nov 11 01:55:16 UTC 2024
https://issues.dlang.org/show_bug.cgi?id=24838
--- Comment #8 from Manu <turkeyman at gmail.com> ---
I think you've completely missed the point...
Yes, me code DOES squirrel away the address of func, that is literally the
point of this bug report.
The point is, the lambda doesn't access anything at all from the closure except
'this', and so rather than creating a closure like:
struct Closure
{
MyClass this;
}
void func(Closure* closure) { closure.this.doSomething(); }
The closure is pointlessly allocated; there's no reason to synthesise the
function this way. If the Closure ONLY references `MyClass this`, then func has
no reason to allocate a closure and bind it to the delegate; it could just
synthesise this function:
func(MyClass this) { this.doSomething(); }
This bypasses the closure since it has no reason to exist, and just places
`this` into the delegate, and so for all intents and purposes, the lambda is
just a normal method.
This optimisation is similarly valid for any closure which closes over exactly
one pointer. It could even further be generalised such that any closure which
closes over exactly a single size_t-sized POD just write that value to the
'this' pointer of the delegate (essentially small-struct optimisation embedded
in the delegate), and then the lambda naturally receives it as first argument
when the delegate it called.
There's a quite broad category of optimisation here; it's inefficient and
pointless in most cases for a closure to be allocated with just one member...
and it also has the nice advantage that in cases where a delegate has only a
single reference (it, 'this'), then it doesn't need to allocate a closure at
all, and so it's naturally `@nogc`.
--
More information about the Digitalmars-d-bugs
mailing list