Variable-length stack allocated arrays

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Jan 12 06:58:55 PST 2010


dsimcha wrote:
> == Quote from Lars T. Kyllingstad (public at kyllingen.NOSPAMnet)'s > > It's got the
> following advantages over alloca:
>>> 1.  Can't overflow unless you're completely out of address space.  As a last
>>> resort, it allocates another chunk of memory from the heap.
>> When all chunks in a block have been TempAlloc.free()'ed, is the block
>> GC.free()'ed as well?  Or is the memory retained for future use?  (And
>> if the answer to the last question is 'no', is there a reason not to
>> retain the memory until the program exits, or at least to include an
>> option to?)
>> -Lars
> 
> The memory is freed according to heuristics.  Here's a brief description:
> 
> 1.  All state is thread-local.  Unless TempAlloc needs to go to the main heap,
> there is never any type of synchronization.
> 
> 2.  Each chunk is 4 MB.  I've realized that this may be overkill and am thinking
> of reducing it to 1 MB or 512K.  This is controlled by an enum, so it would be a
> trivial change.

I suppose it depends on what you're using it for. For maximum 
flexibility, you could do this:

   struct CustomTempAlloc(uint blockSize)
   { // current TempAlloc code here }

   // Default is 4MB
   alias CustomTempAlloc!(4U * 1024U * 1024U) TempAlloc;


> 3.  Chunks are stored in a stack (yes, a stack of stacks).  Half of the unused
> chunks are freed anytime there are 2x as many unused chunks as used chunks.
> Usually 4MB per thread in temp buffer space is plenty, though.

Thanks for the explanation!

-Lars



More information about the Digitalmars-d mailing list