dynamic array .length vs .reserve - what's the difference?

Ali Çehreli acehreli at yahoo.com
Thu Jul 30 16:33:22 UTC 2020


On 7/30/20 8:58 AM, wjoe wrote:

>          b.reserve(n);
>          b.length = n;

There may be something that I don't know but I think assigning to the 
.length property alone should be the same as reserving and then assigning.

reserve is supposed to make sure no memory will be allocated as elements 
are added.

capacity tells how many elements can be added without memory is 
allocated. However, the D runtime does its best to elide actual memory 
allocation if there is room beyond the array's last element and it's 
safe to do so.

This article is considered a must-read for understanding what is going 
on behind the scenes:

   https://dlang.org/articles/d-array-article.html

I tried to introduce the concept of slices "sharing elements" as well as 
how .capacity is used to determine whether sharing will be terminated, here:

   http://ddili.org/ders/d.en/slices.html#ix_slices..capacity

Ali



More information about the Digitalmars-d-learn mailing list