Which algorithm is used in List to dynamically allocate memory?

后端 未结 6 1303
渐次进展
渐次进展 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条回答
  •  耶瑟儿~
    2021-01-18 23:17

    TO answer your question:

    It is true, C#'s List implementation uses an internal array that is

    1. Serializable
    2. Thread-safe
    3. Implements IEnumerable (which means it can be LINQ Queried, foreached etc)
    4. Binary Searched

    and so on

    Hence, I would ask you to use List instead of your own List.

    Oh and btw, if you want the source code of List from Microsoft, then here it is

    List.cs

    EDIT

    The source code of EnsureCapacity in List is:

        // 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;
            }
        }
    

提交回复
热议问题