Can anyone explain how List<T> works internally in C#?
public List<ConvData> pdetails = new List<ConvData>();
How is it stored? What exactly happens when we call pdetails.Add();
List is implemented the same way C++'s vector, meaning the implementation allocate an array of a predefined size, fills that array, and when you want to add an element and the array is full the implementation allocate a new array, bigger, copies all values to the new array, and then adds the new value. This results with an AVERAGE performance of O(1) when adding, but not always.
Just take a look at the reference source from Microsoft and see how it works in detail.
Right now, the Add method looks like this:
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}
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