Trying to avoid the GC

Adam D. Ruppe via Digitalmars-d digitalmars-d at puremagic.com
Wed Dec 31 05:52:02 PST 2014


On Wednesday, 31 December 2014 at 13:38:05 UTC, Shachar Shemesh 
wrote:
> alias dtype = void delegate(int i);
> void func(T)( T d )


Try writing that:

void func(scope dtype d)

instead. Or (scope T d) should do it too if you need it to be 
templated. The scope keyword tells the compiler that you promise 
not to escape it from that scope, so it is safe to use stack 
memory. Should prevent the copying to gc of a delegate. (One of 
the few places the scope keyword is actually implemented to do 
something!)

Alternatively, an alias parameter to the template can take a 
predicate - assuming it is static - and generate a new function 
for each one.

void func(alias pred)() {
    foreach(i; 0 .. 10)
        pred(i);
}

Then use it with func!(predicate)(). This is what Phobos 
std.algorithm uses. It can be trickier to actually make it work 
though.

But scope should get you to the next step easily. gdc might even 
inline the delegate then, though I doubt dmd will. Even dmd ought 
not to GC with it tho.


More information about the Digitalmars-d mailing list