Long term @nogc / allocators usage

Dicebot via Digitalmars-d digitalmars-d at puremagic.com
Mon Jul 25 04:17:57 PDT 2016


@nogc code is quite different from idiomatic "casual" D code and 
one is expected to make sacrifices to go for it. Here are some 
approaches I decided for myself:

On Sunday, 24 July 2016 at 15:34:55 UTC, Lodovico Giaretta wrote:
> Now, there are some cases in which you cannot avoid the managed 
> allocations:
> 1) throwing exceptions: these should not be abandoned in favor 
> of other solutions; IMHO, they should be easily usable in @nogc 
> code; switching to error codes or user-defined callbacks is not 
> feasible in general;

Use pre-allocated exception instances. Throwing itself doesn't 
require GC, only allocating exception does. You can possibly 
screw up exception chaining this way but this is a very minor 
loss.

> 2) returning arrays: sometimes you just can't avoid this: if 
> your function must return a string, than it has to allocate it 
> (unless it's a slice of some input)

If it can't be avoided, this is not @nogc code and there is no 
point in pretending otherwise. Use ranges and sinks instead to 
move allocations decisions up the call chain. Note that with sink 
approach you want be able to mark function itself @nogc (because 
sink delegate allocates) but you can mark unittest block that 
verifies there are no _other_ allocations:

void foo ( alias sink_dg ) ( )
{
     sink_dg("abc");
}

@nogc unittest
{
     void noop_sink ( const(char)[] chunk ) @nogc { }
     foo!noop_sink();
}


More information about the Digitalmars-d mailing list