From d2db18b36e1594408a8be1ab61ac92608781d54c Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Thu, 23 Feb 2017 03:15:57 +0000 Subject: [PATCH] Faster List Add (dotnet/coreclr#9539) Commit migrated from https://github.com/dotnet/coreclr/commit/7d9e01719d29b9dda2d1f53fe15461f9b371e604 --- .../src/System/Collections/Generic/List.cs | 28 ++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/coreclr/src/mscorlib/src/System/Collections/Generic/List.cs b/src/coreclr/src/mscorlib/src/System/Collections/Generic/List.cs index 82f6e41..d654cd2 100644 --- a/src/coreclr/src/mscorlib/src/System/Collections/Generic/List.cs +++ b/src/coreclr/src/mscorlib/src/System/Collections/Generic/List.cs @@ -207,11 +207,31 @@ namespace System.Collections.Generic // 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 ((uint)size < (uint)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; + EnsureCapacity(size + 1); + _size = size + 1; + _items[size] = item; } int System.Collections.IList.Add(Object item) -- 2.7.4