GC question

thedeemon via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 4 03:09:21 PST 2017


On Wednesday, 1 February 2017 at 06:58:43 UTC, osa1 wrote:
> I'm wondering what
> are the implications of the fact that current GC is a 
> Boehm-style conservative
> GC rather than a precise one, I've never worked with a 
> conservative GC before.
> Are there any disallowed memory operations? Can I break things 
> by not following
> some unchecked rules etc. ? How often does it leak? Do I need 
> to be careful
> with some operations to avoid leaks?

Here's some practical perspective from someone who released a 
32-bit video processing app in D with thousands of users.
When developing with GC in D you need to keep in mind 3 key 
things:

1) The GC will treat some random stack data as possible pointers, 
and some of those false pointers will accidentally point to some 
places in the heap, so for any object in GC heap there is a 
probability that GC will think it's alive (used) even when it's 
not, and this probability is directly proportional to the size of 
your object.

2) Each GC iteration scans the whole GC heap, so the larger your 
managed heap, the slower it gets.

Main consequence of 1 and 2: don't store large objects (images, 
big file chunks etc.) in the GC heap, use other allocators for 
them. Leave GC heap just for the small litter. This way you 
practically don't leak and keep GC pauses short.

3) GC will call destructors (aka finalizers) for the objects that 
have them, and during the GC phase no allocations are allowed. 
Also, since you don't know in which order objects are collected, 
accessing other objects from a destructor is a bad idea, those 
objects might be collected already.

Main consequence of 3: don't do silly things in destructor (like 
throwing exceptions or doing other operations that might 
allocate), try avoiding using the destructors at all, if 
possible. They may be used to ensure you release your resources, 
but don't make it the primary and only way to release them, since 
some objects might leak and their destructors won't be called at 
all.

If you follow these principles, your app will be fine, it's not 
hard really.


More information about the Digitalmars-d-learn mailing list