开发者

How is List.Clear() implemented in C#?

I assume it uses an array to implement List. How is List.Clear() implemented? Does it actually clean up the array or just make a new array for this list?

public class List {

    private Array _array;

    public void Clear1 () {
        _array.length = 0;
    }
    public void Clear2 () 开发者_运维百科{
        _array = new Array();
    }
}


Like this (using .NET Reflector):

public void Clear()
{
    if (this._size > 0)
    {
        Array.Clear(this._items, 0, this._size);
        this._size = 0;
    }
    this._version++;
}

As you see, it just clears the same array. It probably assumes that if you're reusing the same list, you'll probably want to refill it with roughly the same amount of data. If you want to release the array, you'll need to create a new List instance.


MSDN:

Count is set to 0, and references to other objects from elements of the collection are also released.

Capacity remains unchanged. To reset the capacity of the List, call the TrimExcess method or set the Capacity property directly. Decreasing the capacity reallocates memory and copies all the elements in the List. Trimming an empty List sets the capacity of the List to the default capacity.

This method is an O(n) operation, where n is Count.


As of .NET 4.0, it does the following:

  1. Zeros out the backing array with an Array.Clear call. This effectively makes it an O(n) operation.
  2. Sets size to 0.
  3. Increments the internal version number so that active enumerators will throw InvalidOperationExceptions if MoveNext is called on them.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜