[phobos] Array preallocate function

Steve Schveighoffer schveiguy at yahoo.com
Tue Feb 23 09:10:41 PST 2010

----- Original Message ----

> From: Andrei Alexandrescu <andrei at erdani.com>
> Steve Schveighoffer wrote:
> > This is a good idea.  I still think a function to do this should be
> > available, so you can do the allocation in one step instead of
> > declaring an array and then setting its capacity.
> > 
> > What about the issue of shrinking the allocated size as in the loop I
> > showed?  Should this be allowed via builtin arrays or reserved to a
> > wrapper?
> I think regardless of what we do, there will be people who will say 
> buffer.length = 0 if they want to reuse a buffer. I think we should do something 
> sensible in such cases. The case I don't think we want to endorse as an idiom is 
> "for efficiency, initialize needlessly a large buffer and then assign its length 
> to zero".

Discouraging that case doesn't go very far when we allow it to do what it did before.  I think by disallowing it, you discourage it more than adding any new functions.

If someone has an array, and they want to trim one element off the end, it would be feasible they may write:

array.length -= 1;

vs the more verbose

array = array[0..$-1];

Letting these two statements do something different is a mistake in my mind.

What about a "minimize" function, which simply truncates any "allocated" length after an array.  So you would reset an array via:

arr.length = 0;

The advantage here is the array's length is not affected, just the allocated length is reduced to match the array's length.  There are less invalid cases to worry about (i.e. "shrinking" to something larger doesn't make any sense).



More information about the phobos mailing list