From 9c8554a7c1e3f531d7babb70f699a420ffb1d20f Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Wed, 22 Feb 2017 00:51:08 +0000 Subject: [PATCH] Faster List Add --- .../src/System/Collections/Generic/List.cs | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs index 82f6e41c361e..348b292f318a 100644 --- a/src/mscorlib/src/System/Collections/Generic/List.cs +++ b/src/mscorlib/src/System/Collections/Generic/List.cs @@ -207,11 +207,32 @@ public class List : IList, System.Collections.IList, IReadOnlyList // Adds the given object to the end of this list. The size of the list is // 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; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(T item) + { + var array = _items; + var size = _size; + _version++; + if (size < array.Length) + { + _size = size + 1; + array[size] = item; + } + else + { + AddWithResize(item); + } + } + + // Non-inline from List.Add to improve its code quality as uncommon path + [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)