Dynamic Array reserve

Steven Schveighoffer schveiguy at yahoo.com
Sat Dec 16 23:58:57 UTC 2017


On 12/16/17 5:48 PM, Vino wrote:
> On Saturday, 16 December 2017 at 16:46:49 UTC, Jacob Carlborg wrote:
>> On 2017-12-16 15:11, Vino wrote:
>>> Hi All,
>>>
>>>   Request your help on reserve an dynamic array when the capacity is 
>>> reached to a point(eg: 80%) so the array to extend the reserve by 
>>> next 20%
>>>
>>> Example:
>>> Array!string Test;
>>> Test. reserve(100) - Initall
>>> Test =(.........) - The number of entries are dynamic
>>> if (array.capacity > 80%) { array.reserve(100+20%)
>>
>> There's a "capacity" property which you can use. Compare that to the 
>> length of the array to know when it has reach 80%.
> 
> Hi Jacob,
> 
>    Thank you , yes we can use the length property and calculate the 
> capacity, but the question is how to implement it dynamically, so let me 
> explain a bit further.

Array should automatically increase the size as you need more data. And 
it amortizes the extensions, so instead of adding a constant number of 
elements (as you are proposing), it multiplies the capacity by some 
value. So you end up with better performance.

I think you are fine to just use Array and not worry about the 
reallocations, they are handled automatically.

-Steve


More information about the Digitalmars-d-learn mailing list