Now I have an algorithm for dynamically allocating memory on an array:
List
uses an array internally, and it uses a similar strategy as you - it doubles the size of the array if the length would go over the length of the array. However, it doesn't make it smaller should the size be way smaller.
The relevant method in mscorlib
:
private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}
The resizing of the array actually happens in the setter of List
.