Feature suggestion: in-place append to array
grauzone
none at example.net
Thu Mar 4 08:43:27 PST 2010
Steven Schveighoffer wrote:
> On Thu, 04 Mar 2010 04:02:46 -0500, KF <kfleszar at gmail.com> wrote:
>
>> I hope this is the right place to post it.
>> In my work, I often need to add elements at the end of dynamic arrays
>> and remove them from the end. This incremental changes would most
>> conveniently be performed by a~=e for addition of e at the end of a,
>> and say a=a[0..$-1]. Unfortunately, ~= always creates a copy and
>> is thus too time consuming.
>
> No, it does not create a copy. a = a ~ e always creates a copy, a ~= e
> appends in place if possible. This still will be slower than appender,
> but in the next release of DMD it will be much faster than the current
> release.
>
> With the next release of DMD, a = a[0..$-1] will shrink the array, but
> the next append to a will reallocate. There will be a function to get
> around this, but use it only if you know that the data removed from the
> end isn't referenced anywhere else.
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.
> -Steve
More information about the Digitalmars-d
mailing list