Idea for avoiding GC for lambdas

Elronnd elronnd at elronnd.net
Mon Jun 21 22:19:12 UTC 2021


The reason delegates involve GC is because the closure is shared. 
  E.G.:

int x;
auto f = () => x++;
auto g = () => x++;
f(); //0
g(); //1
f(); //2

f and g share a reference to the same x, so we need GC to know 
when to clean it up.

Your proposal is essentially a value delegate; the __context 
stuff makes that explicit, but it's not actually fundamentally 
different from the current scheme, it's just that the context 
becomes a value type rather than a reference type.

I think value closures are a good idea--for semantics reasons 
too, not just avoiding gc--but problematic for existing APIs to 
support, because every value closure will have a different type 
and a different size.  And we have enough problems already with 
compile time template explosion :)

WRT your proposal, I think it would be better to introduce an 
alternate syntax for function literals: we have  function(parm) 
=> ret  and  delegate(parm) => ret; add  valuedelegate(parm) => 
ret.  And make it so that valuedelegate.ptr is a struct (the 
context struct) so you can still introspect it if needed.

> I realize there are implications if the context parameter is 
> mutable, so perhaps we would have to require only const contexts

Why?  What you've made is basically a functor where the compiler 
infers the context; structs are received by reference (by their 
methods).  If the context were shared, then const wouldn't be 
enough; it would have to be immutable to retain value semantics.  
But the whole point of this was to avoid sharing (and hence GC), 
so I don't see why that would be a problem.


More information about the Digitalmars-d mailing list