I don't like slices in D

Steven Schveighoffer schveiguy at yahoo.com
Tue Jan 14 20:11:01 PST 2014


On Fri, 18 Oct 2013 01:45:30 -0400, Jesse Phillips  
<Jesse.K.Phillips+D at gmail.com> wrote:

> On Thursday, 17 October 2013 at 20:03:53 UTC, Vitali wrote:
>>   arrPtr1 = arr.ptr;
>>   arr.reserve(5);     // reserve capacity
>>   arrPtr2 = arr.ptr;
>>   assert(arrPtr1 != arrPtr2); // ok, this makes sense
>>   assert(arr.capacity==7); // ok, this makes not so
>>   // much sense, but it's bigger than 5,
>>   // I guess it's ok
>>
>>   // I reserved extra capacity. I got more
>>   // than I needed, but ok.
>
> It will reserve enough memory for the requested size, in doing so it  
> will allocate on some hardware friendly boundary. (Others here have a  
> better grasp on why and what that is).

The memory allocator works in powers of 2 bytes from 16 to PAGE size. A D  
array has runtime data to maintain inside the block, which is why the  
resulting array length is a power of 2 - 1.

For instance, 5 integers would only fit into a block of 32 bytes. You may  
expect a capacity of 8, and it would be true, except the runtime has to  
actually store the capacity somewhere, so it consumes some bytes to do  
that inside the block itself. So a block of 8 ints becomes a block of 7  
ints. There is also the issue of needing a sentinel byte between blocks to  
prevent leaking into the next block. So the last element was wasted anyway  
before I added the capacity.

-Steve


More information about the Digitalmars-d mailing list