When does GC run?

Stanislav Blinov stanislav.blinov at gmail.com
Tue Oct 16 12:47:58 UTC 2018


On Tuesday, 16 October 2018 at 09:38:44 UTC, John Burton wrote:

> The information I have found indicates that it runs to free 
> memory when the system runs out of memory to allocate.

No, that is incorrect. By default, here's what's happening:

1) At startup (or first 'new' or GC.malloc) the GC allocates a 
pool of memory.
2) Subsequent calls to 'new' or GC.malloc allocate from that pool.
3) If there isn't enough memory in the pool to allocate, it may 
either:
     a) Pause all your threads and perform a collection sweep, 
unless collection is disabled. If there's still not enough 
contiguous address space in the pool after that, it'll go to b)
     b) Ask the OS for more memory for the pool.

Therefore, implicit automatic collection only occurs when you 
allocate, and only if needed. Explicit collection can be 
requested by calling GC.collect().

> But will this try to use all the system memory or some other 
> amount before trying to garbage collect? If I have a _lot_ of 
> garbage, will it try to collect that before allocating any more 
> system memory? Is this configurable in any way?

If you have a lot of garbage, you should probably allocate in 
advance, disable/enable collection around hot paths and 
explicitly ask for collection in between, or just not use the GC, 
i.e. allocate a block and do your business inside of it.



More information about the Digitalmars-d-learn mailing list