diff --git a/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs b/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs index 482215723c4f..a5ba7b2e9863 100644 --- a/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs +++ b/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; namespace System.Collections.Immutable { @@ -247,7 +248,28 @@ public void Insert(int index, T item) /// Adds an item to the . /// /// The object to add to the . + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) + { + int count = _count; + T[] elements = _elements; + + // PERF: The uint-casts allow the JIT to eliminate bound-checks. + // https://github.com/dotnet/coreclr/pull/9773 + if ((uint)count < (uint)elements.Length) + { + elements[count] = item; + _count = count + 1; + } + else + { + AddWithResize(item); + } + } + + // Specify NoInlining so that we are guaranteed an opportunity to service this method + [MethodImpl(MethodImplOptions.NoInlining)] + private void AddWithResize(T item) { int newCount = _count + 1; this.EnsureCapacity(newCount);