Freeing of memory (garbage collection)
Steven Schveighoffer
schveiguy at yahoo.com
Tue Dec 9 06:59:52 PST 2008
"Daniel White" wrote
> Thanks for that reply. I wonder if extending automatic garbage
> collection for malloced memory would be a good idea...
>
>> Only stuff like dynamic
>> arrays, AAs and new'ed stuff gets cleaned up by the GC.
>
> For the above types of allocating memory, is there a way to 'lock' a
> variable and say to D, "don't free this memory until I allow you to",
> and also for it to allow you to free it manually when/if need be?
One thing you can do, that nobody has mentioned yet, is delete memory that
you have allocated using the GC.
Deleting a block of memory that the GC has allocated allows you to reuse
that memory without going through a full GC collect cycle, and so most
likely your performance will be better. Using delete in key spots can be
good.
But using manual memory mangement prevents lots of good designs, so use with
caution.
Lastly, if you are allocating lots of temporary classes, try declaring them
as scope. This allocates the class on the stack if possible. Note that any
memory allocated by the constructor will still go through the GC. Also note
that you can't use a scoped class once its scope is finished. e.g.:
class C
{ ... }
...
while(x > 0)
{
scope c = new C(x--); // c is allocated on the stack. scope keyword
implies the type.
c.doSomething();
// c is deleted from stack at end of loop iteration. No heap activity.
}
-Steve
More information about the Digitalmars-d-learn
mailing list