I have the following question:
List<int> list = new List<int>(10);
for (int i = 0; i < 10; i++)
list.Add(i);
Now list.Count and list.Capacity are 10. It's OK. But what will happen when I will try to remove first item?
list.RemoveAt(0);
Count is now 9 and Capacity still 10, but what happened inside list? List had to go through all the elements like:
list[0] = list[1];
list[1] = list[2];
// etc...
list[9] = null;
?
May be it could be better just to do by myself smthng like:
list[0] = list[list.Count - 1];
? But items order will be changed in this case.
And how long will list.RemoveAt(0) take if I have a List with 10000000 elements with a preinitialized length? Will there be any difference if List will not have preinited length?
UPD:
Looked to the source (didn't know that they are in free access o.O ):
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public void RemoveAt(int index) {
if ((uint)index >= (uint)_size) {
ThrowHelper.ThrowArgumentOutOfRangeException();
}
_size--;
if (index < _size) {
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
So it really has Array.Copy inside. What a pity. Thanks to @TomTom.