Which algorithm is used in List to dynamically allocate memory?

后端 未结 6 1302
渐次进展
渐次进展 2021-01-18 22:18

Now I have an algorithm for dynamically allocating memory on an array:

  • If array is full I create a new array of twice the size, and copy items.
  • If arr
6条回答
  •  旧时难觅i
    2021-01-18 22:53

    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.Capacity.

提交回复
热议问题