diff --git a/src/Nethermind/Nethermind.Core/Collections/ArrayListCore.cs b/src/Nethermind/Nethermind.Core/Collections/ArrayListCore.cs index 00b95e683953..518fb7512842 100644 --- a/src/Nethermind/Nethermind.Core/Collections/ArrayListCore.cs +++ b/src/Nethermind/Nethermind.Core/Collections/ArrayListCore.cs @@ -51,6 +51,15 @@ public static void ClearToCount(T[] array, int count) } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ClearTail(T[] array, int newCount, int oldCount) + { + if (RuntimeHelpers.IsReferenceOrContainsReferences() && newCount < oldCount) + { + Array.Clear(array, newCount, oldCount - newCount); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Add( ArrayPool pool, @@ -108,9 +117,9 @@ public static void ReduceCount( ClearToCount(oldArray, oldCount); pool.Return(oldArray); } - else if (RuntimeHelpers.IsReferenceOrContainsReferences()) + else { - Array.Clear(array, newCount, oldCount - newCount); + ClearTail(array, newCount, oldCount); } [DoesNotReturn] @@ -228,6 +237,7 @@ public static void Insert( public static void Truncate(int newLength, T[] array, ref int count) { GuardIndex(newLength, count, shouldThrow: true, allowEqualToCount: true); + ClearTail(array, newLength, count); count = newLength; }