Feature suggestion: in-place append to array

Steven Schveighoffer schveiguy at yahoo.com
Thu Mar 4 09:19:12 PST 2010


On Thu, 04 Mar 2010 11:43:27 -0500, grauzone <none at example.net> wrote:

> Some sort of "resetAndReuse" function to clear an array, but enabling to  
> reuse the old memory would be nice:
>
> int[] a = data;
> a = null;
> a ~= 1; //reallocates (of course)
> a.length = 0;
> a ~= 1; //will reallocate (for safety), used not to reallocate
> resetAndReuse(a);
> assert(a.length == 0);
> a ~= 1; //doesn't reallocate
>
> This can be implemented by setting both the slice and the internal  
> runtime length fields to  0.
>
> Additionally, another function is necessary to replace the old  
> preallocation trick:
>
> //preallocate 1000 elements, but don't change actual slice length
> auto len = a.length;
> a.length = len + 1000;
> a.length = len;
>
> As I understood it, this won't work anymore after the change. This can  
> be implemented by enlarging the array's memory block without touching  
> any length fields.
>
> I'm sure the function you had in mind does one of those things or both.

proposed usage (as checked in a couple days ago):

int[] a;
a.setCapacity(10000); // pre-allocate at least 10000 elements.
foreach(i; 0..10000)
    a ~= i; // no reallocation
a.length = 100;
a.shrinkToFit(); // resize "allocated" length to 100 elements
a ~= 5; // no reallocation.

I will probably add a function to do the preallocation of a new array  
without having to write two statements.  Also, one cool thing about this  
that was not available before is that increasing the capacity will not  
initialize the new data as long as "no pointers" flag is set.  For  
pointer-containing elements, the contents must be initialized to zero to  
prevent false positives during collection.

Note that setCapacity is supposed to be a property (i.e. a.capacity =  
10000), but the compiler doesn't support this, I added a bug (feature)  
request for this (3857).

There is also a readable capacity property to get the number of elements  
the array could grow to without reallocation, a feature that may be useful  
for tuning.

Also the name "shrinkToFit" may not be final :)  I wanted to call it  
minimize, but there were objections, and shrinkToFit is easy to  
search/replace later.

-Steve



More information about the Digitalmars-d mailing list