[Dlang-study] [lifetime] Local garbage collector for pure functions

Ralph Tandetzky ralph.tandetzky at gmail.com
Wed Dec 23 04:49:43 PST 2015


Some pure functions use the garbage collector, but the allocated 
memory cannot escape the function due to its signature. Therefore 
all the created garbage could be locally collected at function 
exit.

     int f( const int[] arr ) pure; // @localgc ?

The only requirements on the function would be, that they are 
pure and that return types and argument types do not allow 
allocated memory to escape.

And here's how I imagine it to work: At function entry the GC 
could be instructed to use a region allocator. At function exit 
the whole allocated memory is discarded all at once. The only 
problem I see with this, is that internally functions could be 
called which allocate memory in a tight loop producing to much 
garbage. Hence, collecting the garbage may be necessary in 
extreme cases. Therefore, the region allocator should not allow 
to much memory to be allocated, but fall back to garbage 
collection, if a lot of memory is requested. The good news is 
though, that this garbage collection can be local to our pure 
function.

Therefore, it is not necessary to freeze the whole application or 
to scan the whole stack and global memory. Instead, only the 
running thread needs to scan the stack from our function upwards 
and the local pool of allocated memory and collect there.

Pushing it all a little further: In templated code, where the all 
function definitions are visible to the compiler and no 
allocations are done in loops, heap allocations could be 
transformed into stack allocations by the compiler and the 
functions could even be marked @nogc. Standard library algorithms 
could use lambdas with captures like crazy again and do things 
idiomatically and functional in D while still ensuring @nogc.

What do you think?


More information about the Dlang-study mailing list