Array length & allocation question

Dave Dave_member at pathlink.com
Thu Jun 8 11:39:40 PDT 2006


Robert Atkinson wrote:
> Quick question concerning Array lengths and memory allocations.
> 
> When an array.length = array.length + 1 (or length - 1) happens, does the system
> only increase (decrease) the memory allocation by 1 [unit] or does it internally
> mantain a buffer and try to minimise the resizing of the array?
> 
> I think I can remember seeing posts saying to maintain the buffer yourself and
> other posts saying it was done automatically behind the scenes.
> 
> 

Setting the array length does just that and nothing more or less. But 
using the the array concatenation operator (~) will preallocate some space.

time this:

     int[] arr;
     for(int i = 0; i < 1000000; i++)
     {
         arr.length = arr.length + 1;
         arr[i] = i;
     }

vs this:

     int[] arr;
     for(int i = 0; i < 1000000; i++)
     {
         arr ~= i;
     }



More information about the Digitalmars-d-learn mailing list