Designing with the GC out of mind

Adam D. Ruppe destructionator at gmail.com
Tue Aug 6 05:41:25 PDT 2013


On Tuesday, 6 August 2013 at 07:19:40 UTC, JS wrote:
> 1. Is there a way to determine what the GC is doing?

It is probably easiest to just run it in a debugger, and set a 
breakpoint on gc_malloc and gc_qalloc. When it breaks, you can 
see where it is, then continue to carry on.

You can also tell where the gc runs by carefully reviewing the 
code:

1) any instance of "new", obviously

2) any use of array ~ array. Binary ~ on other types doesn't 
necessarily run the gc, since it could be overloaded, but 
generally does. (If you want to avoid gc, a ~ b is something I'd 
avoid entirely.)

3) Some uses of a ~= b. This doesn't necessarily allocate, it 
might be appending to reserved space or be overloaded. If a is a 
built in array though and you're looking at the code, assume it 
allocates and do something else.

4) Passing a nested delegate or lambda to another function, 
sometimes. It won't if a) the receiving function marks the 
delegate argument as scope, or b) the function doesn't reference 
any variables.

But generally if you see a non-scope delegate, assume it 
allocates.

5) Any array literal that isn't static immutable allocates. 
Hopefully this will be fixed soon, but right now they all do... 
even if the array literal is in an enum!

ummm... I think I might be forgetting something, but I'm pretty 
sure these are all the major ones.

Anything that allocates might call the gc collect.


So to sum up: search your code for "new", "~", calling functions 
that receive "delegate", and "[a,b,c...]" and you'll have an idea 
as to where the gc might run in your code.

> I suppose I can modify the sources, but is there an easier way?

What about writing your own external alloc function like 
std.conv.emplace? Then you'd do it just at the creation site 
without modifying the class.

> (which I think is required over sizeof, classInstanceSize, 
> etc... to prevent slicing).

Check out typeid(MyClass).init as well...


More information about the Digitalmars-d mailing list