allocate array with new

Steven Schveighoffer schveiguy at yahoo.com
Wed May 16 10:52:12 PDT 2012


On Wed, 16 May 2012 12:52:33 -0400, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> On Wednesday, May 16, 2012 11:51:59 Steven Schveighoffer wrote:
>> Well, the D GC is conservative, and will always be at least partly
>> conservative. So freeing memory manually is not really a crime.
>
> The idea with a GC is that it's supposed to manage the memory allocated
> through it. So, if you're worrying about freeing GC memory, you're  
> fighting the
> GC and how it works. And unless you're keeping very close track of the  
> number
> of reference to a particular chunk of memory, freeing it manually is
> dangerous. So, anyone looking to use delete is generally going about  
> things
> the wrong way.
>
> However, it _is_ true that sometimes you need to intervene in order to  
> get
> sections of code as performant as they need to be (particularly since D's
> current GC is not the most performant), which is part of the reason that
> core.memory provides what it does. But it should generally be something  
> used
> when it's clear that you need that extra performance, not as a matter of
> course, because using it is inherently unsafe. If there's something that  
> you
> know ahead of time needs to have more deterministic deallocation, then  
> it's
> probably better to be use malloc and free with ref-counting than trying  
> to
> manually manage GC memory.

Where the GC gets into trouble is with allocation of large chunks of data.

If the data 'contains pointers', it creates a very good chance that the  
data keeps some unknown number of blocks from being deallocated.

And just by the sheer fact of how big the data is, it's bound to be  
pointed at by some piece of stack data, global data, or TLS data.

So you can go a long way by manually managing larger chunks of data.  I  
think it's worth worrying about as you get into large chunks (on the order  
of 10MB or more).

What really really sucks about this is, as you allocate larger chunks of  
data, the chances that the GC incorrectly keeps garbage memory get  
larger.  In other words, the more memory you allocate, the less likely it  
is that the GC will give you some of it back to you!

Precise GC will help this *tremendously*, but I'm unsure if we'll ever get  
to the point of having a fully-precise GC.  There will always be a need to  
do manual freeing of memory.

-Steve


More information about the Digitalmars-d-learn mailing list