Garbage Collector?

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 28 10:58:37 PDT 2017


On Fri, Apr 28, 2017 at 04:03:18PM +0000, bachmeier via Digitalmars-d wrote:
> On Friday, 28 April 2017 at 15:23:18 UTC, H. S. Teoh wrote:
> 
> > you could save yourself the bug by writing:
> > 
> > 	auto x = malloc(...);
> > 	scope(exit) free(x);
> > 	// ... however many pages of stuff you want, you don't have to
> > 	// remember to write free() afterwards!
> > 
> > Yes, D comes with a GC... doesn't mean you have to use it if you
> > don't want to, though!
> 
> I usually use the GC, so I have limited knowledge in this area. How
> common is this pattern in D code? Is it better than using reference
> counted structs? Is there any advantage to using the GC in this
> scenario?

To be honest, in my own D code I'm not overly concerned with the GC, and
even when I am, and want to control when / how often the GC collects, I
usually just use GC.disable() and then GC.collect() explicitly.  I've
seen performance gains of about 30-40% just by carefully reducing the
frequency of GC collections (IMO the default is a bit too eager), but of
course that depends on exactly what your application is doing.  In my
case, that was in the context of batch-oriented, CPU-intensive
computations that allocate often and mostly keeps live data.  YMMV if
your program is doing something else or has other patterns of memory
access.

But my point was that, if you really wanted to, you *could* use C-style
memory management in D code. D won't stop you from doing that. The
malloc heap is distinct from the GC heap so you won't run into
conflicts.  Of course, that also means you can't use D features that
currently require the GC, such as closures and dynamic arrays. But if
you're doing C-style memory management you probably already want to
implement your own way of handling array allocations and closure
functionality anyway. You can still pass slices of things around to
things like Phobos range algorithms (excepting the few that might
allocate -- hence marking your code with @nogc for the compiler to
enforce this), so generally a decent chunk of Phobos should still be
usable.

Even Phobos itself uses malloc/free directly in several places, for
various reasons, so I wouldn't say it's exactly a foreign thing to do in
D code.


> I would like to add this info to the wiki (I don't seen it there).

That would be very nice, thanks!


T

-- 
Give a man a fish, and he eats once. Teach a man to fish, and he will sit forever.


More information about the Digitalmars-d mailing list