Thanks to visit codestin.com
Credit goes to github.com

Skip to content

List<T> Insert() - optimize memory copying #89915

@glenn-slayden

Description

@glenn-slayden

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).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions