I was looking at List<T> in ReferenceSource and found that List<T>.Add (also Remove and RemoveAt) actually copies the internal list array (T[] _items) into a new array with the new modifications; they actually call Array.Copy method, that calls the CLR-internal method Copy. I don't know how does that internal method (Copy) work, but if it does as what it was called (copying), then I believe this would be a performance-expensive way for adding items to or removing items from a list; and I'm wondering why there's no actual add and remove?
The Add method does not always copy the internal array. When the array is filled with items it's items are moved to a new one, twice the size.
As far as Remove goes. You can see that it will perform the copy operation only if the index is smaller than the _size. This means that if you attempt to remove the last element from the list, there is no need for the internal array to resize, it simply removes the last element. However, if you want to remove an element from the middle you need to create "shift" left the elements after the removed index.
This is why if you are to remove many elements from arbitrary indexes in a List<T> you another data structure is recommended, such as LinkedList.
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