diff --git a/Recyclable.Collections/RecyclableList.cs b/Recyclable.Collections/RecyclableList.cs index c4a3a7d..6609e9e 100644 --- a/Recyclable.Collections/RecyclableList.cs +++ b/Recyclable.Collections/RecyclableList.cs @@ -281,15 +281,23 @@ namespace Recyclable.Collections _ = EnsureCapacity(targetCapacity); } - int blockSize = _blockSize, targetBlockIndex = _lastBlockIndex; + int blockSize = _blockSize, + targetBlockIndex = _lastBlockIndex, + memoryBlockCount = _memoryBlocks.Length; + Span itemsSpan = new(items); - Span memoryBlocksSpan = new(_memoryBlocks, 0, _memoryBlocks.Length); + Span memoryBlocksSpan = new(_memoryBlocks, 0, memoryBlockCount); Span targetBlockArraySpan = new(memoryBlocksSpan[targetBlockIndex], _nextItemIndex, blockSize - _nextItemIndex); while (targetBlockArraySpan.Length <= itemsSpan.Length) { itemsSpan[..targetBlockArraySpan.Length].CopyTo(targetBlockArraySpan); itemsSpan = itemsSpan[targetBlockArraySpan.Length..]; targetBlockIndex++; + if (targetBlockIndex == memoryBlockCount) + { + break; + } + targetBlockArraySpan = new(memoryBlocksSpan[targetBlockIndex], 0, blockSize); }