Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.

Commit

Permalink
Faster List Add
Browse files Browse the repository at this point in the history
  • Loading branch information
benaadams committed Feb 22, 2017
1 parent 0b4e58a commit 828225c
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/mscorlib/src/System/Collections/Generic/List.cs
Expand Up @@ -208,10 +208,34 @@ public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
// 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;
public void Add(T item)
{
if (_size < _items.Length)
{
AddWithoutResize(item);
}
else
{
AddWithResize(item);
}
}

private void AddWithoutResize(T item)
{
var size = _size;
_version++;
_size = size + 1;
_items[size] = item;
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void AddWithResize(T item)
{
var size = _size;
_version++;
_size = size + 1;
EnsureCapacity(size + 1);
_items[size] = item;
}

int System.Collections.IList.Add(Object item)
Expand Down

0 comments on commit 828225c

Please sign in to comment.