Patterns to avoid GC with capturing closures?

Peter Alexander peter.alexander.au at gmail.com
Fri Aug 24 15:18:13 UTC 2018


Consider this code, which is used as an example only:

auto scaleAll(int[] xs, int m) {
   return xs.map!(x => m * x);
}

As m is captured, the delegate for map will rightly allocate the 
closure in the GC heap.

In C++, you would write the lambda to capture m by value, but 
this is not a facility in D.

I can write scaleAll like this:

auto scaleAll(int[] xs, int m) @nogc {
   return repeat(m).zip(xs).map!(mx => mx[0] * mx[1]);
}

So that repeat(m) stores m, but it is quite hacky to work like 
this.

I could write my own range that does this, but this is also not 
desirable.

Are there any established patterns, libraries, or language 
features that can help avoid the GC allocation in a principled 
way here?


More information about the Digitalmars-d-learn mailing list