When List <T> resizes, is extra capacity added?

When a list is resized because there is no excess capacity, how much capacity is added? only 1? Or adds capacity (doubles the total capacity)?

+3
source share
4 answers

Capacity will double.

This is controlled by the following source:

// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min, 
// whichever is larger.
private void EnsureCapacity(int min) { 
    if (_items.Length < min) { 
        int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
        if (newCapacity < min) newCapacity = min; 
        Capacity = newCapacity;
    }
}

_defaultCapacityis const intequal 4.

+8
source

These are EnsureCpacity methods, as the reflector sees this. The size will be doubled :)

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;
    }
}
+4
source

It looks like it doubles based on the following code:

int initialCapacity = 100;
List<string> list = new List<string>(initialCapacity);

Console.WriteLine(list.Capacity);

for(int i = 0; i < list.Capacity; i++){
    list.Add("string " + i);    
}

list.Add("another string");

Console.WriteLine(list.Capacity); // shows 200, changes based on initialCapacity
+2
source

Usually double.

0
source

Source: https://habr.com/ru/post/1774359/


All Articles