new T[size] vs .reserve

Steven Schveighoffer schveiguy at yahoo.com
Sat Feb 2 13:33:23 PST 2013


On Sat, 02 Feb 2013 11:36:28 -0500, Namespace <rswhite4 at googlemail.com>  
wrote:

> Currently something like new ubyte[4]; reserves space for _at least_ 4  
> items.
> But if I want to store now something, the index isn't 0, it's 4.
> Let me explain that on a brief example:
>
> [code]
> import std.stdio;
>
> void main() {
> 	ubyte[] arr = new ubyte[4];
> 	arr ~= 4; // desirable: [4, 0, 0, 0];
> 	writeln(arr); // prints: [0, 0, 0, 0, 4]
> 	
> 	ubyte[] arr2;
> 	arr2.reserve(4);
> 	arr2 ~= 4; // expect: [4, 0, 0, 0];
> 	writeln(arr2); // prints: [4] just as well
> }
> [/code]
>
> So is there any reason why this behaviour is like it is?
>
> As I looked at arr.length and arr.capacity for the first time I was  
> schocked: I want only space for 4 items, but I got space for 15.
> I read in the docs that .reserve extends the space to at least SIZE  
> items, but maybe more. But at that time and still yet I found nothing  
> about new ubyte[SIZE]. So I ask:
> wouldn't it be better, if new ubyte[4] reserves only space for 4 items  
> and reallocs only if I append more than 4?

Heap block sizes start at 16.  One byte overhead is used to store the  
array length, so the minimum size of ANY array allocation is 15 bytes.

Then it doubles to 32, then to 64, then to 128, 256, 512, etc. until you  
get to a page size (4096).  Then it scales linearly by pages.

I think you misunderstand what reserve and append do.  You should read  
this article to understand arrays and appending better:  
http://dlang.org/d-array-article.html

-Steve


More information about the Digitalmars-d-learn mailing list