dynamic array memory allocation

Greg Weber webs.dev at gmail.com
Wed May 16 07:35:22 PDT 2007


Oskar Linde Wrote:

> Greg Weber skrev:
> > I find myself wondering what actually happens when I create a dynamic array and concatenate items onto it.  I think I read in a post that memory will be over-allocated at times to avoid re-allocating.
> > 
> > I think it would help out a lot to have an ability to specify over-allocation.  Something like
> > uint a = [];
> > a.length = 3:10
> > 
> > Where the array length is 3, but you are guaranteed to have memory allocation for 10, so you can be guaranteed that concatenation up to ten will not need to allocate memory.  This could help in the situation where there is concatenation in a loop, and the programmer over-sizes the array before the loop and re-sizes after the loop.
> 
> D no longer clears an array when the size is set to zero, so a reserve 
> method should be as simple as:
> 
> 
> void reserve(T,I)(inout T[] arr, I reservedSize) {
>      static assert(is(I:size_t),"reserve needs an integer size parameter");
>      size_t l = arr.length;
>      if (reservedSize > l) {
>          arr.length = reservedSize;
>          arr.length = l;
>      }
> }
> 
> ...
> 
> int[] a;
> a.reserve(1000);
> for (int i = 0; i < 1000; i++)
> 	a ~= i; // no reallocation
> 
> 
> Care should be taken as always when appending to slices.
> 
> /Oskar

Thanks, that is very useful.  So the next question becomes how can I re-size a dynamic array down to a smaller length and guarantee that (most of) the memory has been freed?



More information about the Digitalmars-d mailing list