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();
}
}
Removes all elements from the List<T>.
To empty an array in C#, use the Array Clear() method: The Array. Clear method in C# clears i.e.zeros out all elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With