-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
runtime/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs
Lines 740 to 744 in 22841c5
if (_size == _items.Length) Grow(_size + 1); | |
if (index < _size) | |
{ | |
Array.Copy(_items, index, _items, index + 1, _size - index); | |
} |
This can be improved for "true" insert cases (i.e., non-append) in any case where resizing is necessary. Currently, when inserting an item at position ix
in a list of N
items, and whenever resizing is required, an excess of N - ix
elements will be unncessarily copied. This is because Grow
sets the Capacity
property, which copies all existing elements as part of resizing the array. This includes copying elements ix ... N-1
into their old positions, which are incorrect considering the current insert operation. Insert
then continutes by immediately shifting those tail elements again by one index position.
Insert
should be optimized to include custom resizing code so that, if resizing is required, the tail elements are only copied once, into their final, correct positions.
This change is expected to be a worthwhile performance improvement, since each List<T>
element can be an arbitrarily large value-type, and the current code involves unnecesasary/excess main memory copying/bus bandwidth as a multiple of sizeof(T)
.