Idea for avoiding GC for lambdas
IGotD-
nise at nise.com
Tue Jun 22 21:58:47 UTC 2021
On Tuesday, 22 June 2021 at 16:13:06 UTC, H. S. Teoh wrote:
>
> The context must be stored *somewhere*, usually on the GC heap,
> which is why delegates depend on the GC. Except for scope
> delegates where it's guaranteed that the parent scope won't go
> out of scope before the delegate does, so the context pointer
> can just point to the stack where the parent's scope is stored.
>
The way C++ works is that a lambda (which is essentially a
template class) when you pass it to a function/method it will be
converted to an std::function. Inside of std::function it will
store context data on the heap. However, it has some "SSO"
capability meaning if the captures are few and small it might fit
into meta data of std::function. Essentially this is the same SSO
(short string optimization) strategy for std::string.
Not sure if this helps but for small lambdas that does simple
things like in the initial example, the context could easily be
stored in the struct.
Now the problem is in D the delegate is very small, while in C++
it is probably more going on like reference counting making
std::function bigger than in D. Making structs bigger isn't
always that popular.
More information about the Digitalmars-d
mailing list