How do you deal with scoped allocations?

Rainer Schuetze r.sagitario at gmx.de
Fri Dec 13 05:31:25 PST 2013



On 09.12.2013 10:13, John Colvin wrote:
> On Sunday, 8 December 2013 at 19:00:29 UTC, Namespace wrote:
>>  > Just using new and GC.free would be fine, but there is really no
>>  > need to burden the GC with this at all; it's a textbook case for
>>  > C's malloc/free.
>> The GC relies also on malloc / free.
>
> Yes, it does. However, obviously it does a lot more than just call
> malloc/free.
>
> If you statically know the lifetime of a chunk of memory, then there
> really is no point invoking all that extra heavyweight code* when you
> can just DIY at no extra cost.**
>
>
> *and adding to the collection burden (if triggered while the memory is
> in scope)
>
> **However, take care with unique pointers from inside the allocated
> block to resources outside the block, as the GC might not be able to
> find them later (see P.S.).


I'm not sold on preferring C's malloc/free instead of the GC.

- The operations GC.malloc and GC.free are very similar to the 
operations of the C functions (if no collection is triggered). The 
current implementation uses OS calls to get more memory from the system, 
only few extra data is allocated via malloc. GC.malloc/free might be 
missing a few optimizations (like lock-free allocations for small memory 
chunks), but they were a lot faster than what dmc's C runtime used to be 
- before the latter was switched to simply call the OS heap functions 
very recently.

- if the GC.malloced memory does not contain pointers (e.g. allocated 
with new int[N]), it isn't scanned by the GC. Determining whether a 
pointer actually refers to GC managed memory or not might be faster for 
unmanaged memory, but this depends on the memory addresses.

- if the GC.malloced memory might contain pointers to GC managed memory 
(like object references), you need to add and remove the memory range so 
that the GC scans the memory, but especially removing the range gets 
pretty expensive if a lot of ranges are added.

>
>
> P.S. does anyone know how the GC interacts with core.stdc.free? I.e. if
> you free a pointer, but don't null the pointer, presumably the GC will
> still scan the memory despite it being freed. Isn't this undefined
> behaviour?

Like thedeemon said, a pointer not pointing to GC managed memory is 
ignored, so this should do no harm.


More information about the Digitalmars-d mailing list