Idiomatic D using GC as a library writer

cc cc at nevernet.com
Mon Dec 5 14:48:33 UTC 2022


On Sunday, 4 December 2022 at 09:53:41 UTC, vushu wrote:
> What are your thoughts about using GC as a library writer?

If your program runs, does some stuff, and terminates, use the GC.
If your program runs, stays up for a while with user occasionally 
interacting with it, use the GC.
If your program runs, and stays up 24/7 doing things in the 
background, use the GC.

If your program is a game meant to run at 60+fps, and any sudden 
skip or interrupt is unacceptable, no matter how minor (which it 
should be), plan carefully about how to manage your game objects, 
because naive GC instantiation and discarding isn't going to cut 
it.  malloc/free, pre-allocated lists, and other strategies come 
into play here.  In a desperate pinch you can also manually 
`GC.free` your GC-allocated objects but this is not recommended.  
The GC can still be used for allocations that are not likely to 
significantly affect performance every frame (strings, occasional 
user-generated information requests, first-load data 
instantiation, Steam avatars, etc) -- but also be even more 
careful when you start mixing and matching.

I find that @nogc is a bit of a false idol though, even in 
situations where the GC is deliberately being avoided.  It simply 
adds too much pain to trying to make everything compliant, and 
certain things just plain don't work (amazingly, the 
non-allocating form of toString can't be @nogc), so I simply 
avoid it and "be careful" (and/or hook into the GC so I can 
monitor if an unexpected allocation happens).  If you're writing 
code that's going to run on a space shuttle or life support 
system, then yeah you might consider the extra effort, but in my 
use cases it simply fails the cost-benefit analysis.

For any strategy, it's still a good idea to have a good 
understanding of or profile your allocations/deallocations so 
you're not just spending memory haphazardly or generating 
excessive collections.


More information about the Digitalmars-d-learn mailing list