Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<Compile Include="$(SharedSourceRoot)UrlDecoder\UrlDecoder.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Metrics\MetricsConstants.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Components\ComponentsActivityLinkStore.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

<Import Project="Microsoft.AspNetCore.Components.Routing.targets" />
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Components/src/NavigationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ protected async ValueTask<bool> NotifyLocationChangingAsync(string uri, string?
}
finally
{
ArrayPool<Func<LocationChangingContext, ValueTask>>.Shared.Return(locationChangingHandlersCopy);
ArrayPool<Func<LocationChangingContext, ValueTask>>.Shared.Return(locationChangingHandlersCopy, handlerCount);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Runtime.CompilerServices;

namespace Microsoft.AspNetCore.Components.Endpoints.FormMapping;

Expand All @@ -17,7 +18,16 @@ public static PooledBuffer Add(ref PooledBuffer buffer, TElement element)
{
var newBuffer = ArrayPool<TElement>.Shared.Rent(buffer.Data.Length * 2);
Array.Copy(buffer.Data, newBuffer, buffer.Data.Length);
ArrayPool<TElement>.Shared.Return(buffer.Data);

if (RuntimeHelpers.IsReferenceOrContainsReferences<TElement>())
{
ArrayPool<TElement>.Shared.Return(buffer.Data, buffer.Count);
}
else
{
ArrayPool<TElement>.Shared.Return(buffer.Data);
}

buffer.Data = newBuffer;
}

Expand All @@ -28,7 +38,16 @@ public static PooledBuffer Add(ref PooledBuffer buffer, TElement element)
public static TCollection ToResult(PooledBuffer buffer)
{
var result = TCollectionFactory.ToResultCore(buffer.Data, buffer.Count);
ArrayPool<TElement>.Shared.Return(buffer.Data);

if (RuntimeHelpers.IsReferenceOrContainsReferences<TElement>())
{
ArrayPool<TElement>.Shared.Return(buffer.Data, buffer.Count);
}
else
{
ArrayPool<TElement>.Shared.Return(buffer.Data);
}

return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public void Dispose()
{
if (_sortedKeys != null)
{
ArrayPool<FormKey>.Shared.Return(_sortedKeys);
ArrayPool<FormKey>.Shared.Return(_sortedKeys, _length);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@
<Compile Include="$(SharedSourceRoot)LinkerFlags.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Components\ComponentsActivityLinkStore.cs" LinkBase="Shared" />
<Compile Include="$(ComponentsSharedSourceRoot)src\HotReloadManager.cs" LinkBase="HotReload" />

<Compile Include="$(SharedSourceRoot)PropertyHelper\**\*.cs" />

<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Microsoft.AspNetCore.Http.HttpResponse</Description>
<Compile Include="$(SharedSourceRoot)Debugger\DictionaryItemDebugView.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Debugger\DictionaryDebugView.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)ValueStringBuilder\ValueListBuilder.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

<ItemGroup>
<Compile Include="$(RepoRoot)src\Shared\TaskToApm.cs" Link="Streams\TaskToApm.cs" />
<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,11 @@ public static async ValueTask StoreAsync(string key, OutputCacheEntry value, Has
{
if (store is IOutputCacheBufferStore bufferStore)
{
await bufferStore.SetAsync(key, new(buffer.GetCommittedMemory()), CopyToLeasedMemory(tags, out var lease), duration, cancellationToken);
ReadOnlyMemory<string> leasedTags = CopyToLeasedMemory(tags, out var lease);
await bufferStore.SetAsync(key, new(buffer.GetCommittedMemory()), leasedTags, duration, cancellationToken);
if (lease is not null)
{
ArrayPool<string>.Shared.Return(lease);
ArrayPool<string>.Shared.Return(lease, leasedTags.Length);
}
}
else
Expand Down
20 changes: 18 additions & 2 deletions src/Middleware/OutputCaching/src/RecyclableArrayBufferWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace Microsoft.AspNetCore.OutputCaching;

Expand Down Expand Up @@ -32,11 +33,19 @@ public RecyclableArrayBufferWriter()
public void Dispose()
{
var tmp = _buffer;
var count = _index;
_index = 0;
_buffer = Array.Empty<T>();
if (tmp.Length != 0)
{
ArrayPool<T>.Shared.Return(tmp);
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ArrayPool<T>.Shared.Return(tmp, count);
}
else
{
ArrayPool<T>.Shared.Return(tmp);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is repeated many times.

What do you think of adding an extra helper method to ArrayPoolExtensions.

ArrayPool<T>.Shared.ReturnAndClearReferences(tmp, count);

In the helper method have a comment that references are cleared from the pool so they can be GCed.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that totally makes sense 👍

}
}

Expand Down Expand Up @@ -120,7 +129,14 @@ private void CheckAndResizeBuffer(int sizeHint)
oldArray.AsSpan(0, _index).CopyTo(_buffer);
if (oldArray.Length != 0)
{
ArrayPool<T>.Shared.Return(oldArray);
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ArrayPool<T>.Shared.Return(oldArray, _index);
}
else
{
ArrayPool<T>.Shared.Return(oldArray);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

<ItemGroup>
<Compile Include="$(SharedSourceRoot)ValueStringBuilder\**\*.cs" />
<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

<ItemGroup>
Expand Down
10 changes: 9 additions & 1 deletion src/Mvc/Mvc.NewtonsoftJson/src/JsonArrayPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Buffers;
using Newtonsoft.Json;
using System.Runtime.CompilerServices;

namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson;

Expand All @@ -26,6 +27,13 @@ public void Return(T[]? array)
{
ArgumentNullException.ThrowIfNull(array);

_inner.Return(array);
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
_inner.Return(array, array.Length);
}
else
{
_inner.Return(array);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<Compile Include="..\..\Mvc.Core\src\Infrastructure\AsyncEnumerableReader.cs" />
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentNullThrowHelper.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)CallerArgument\CallerArgumentExpressionAttribute.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

<ItemGroup>
Expand Down
13 changes: 13 additions & 0 deletions src/Shared/Buffers/ArrayPoolExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Buffers;

internal static class ArrayPoolExtensions
{
public static void Return<T>(this ArrayPool<T> pool, T[] array, int lengthToClear)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the point of this overload? Shouldn't we just always use the ReturnAndClearReferences one?

Copy link
Member

@JamesNK JamesNK Oct 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's for cases were it's known that T is a reference type.

Do you think ReturnAndClearReferences should be used everywhere? I assume RuntimeHelpers.IsReferenceOrContainsReferences<T>() check is optimized away by JIT so they end up being the same anyway.

{
array.AsSpan(0, lengthToClear).Clear();
pool.Return(array);
}
}
19 changes: 17 additions & 2 deletions src/Shared/ValueStringBuilder/ValueListBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,15 @@ public void Dispose()
if (toReturn != null)
{
_arrayFromPool = null;
ArrayPool<T>.Shared.Return(toReturn);

if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ArrayPool<T>.Shared.Return(toReturn, _pos);
}
else
{
ArrayPool<T>.Shared.Return(toReturn);
}
}
}

Expand Down Expand Up @@ -95,7 +103,14 @@ private void Grow(int additionalCapacityRequired = 1)
_span = _arrayFromPool = array;
if (toReturn != null)
{
ArrayPool<T>.Shared.Return(toReturn);
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ArrayPool<T>.Shared.Return(toReturn, _pos);
}
else
{
ArrayPool<T>.Shared.Return(toReturn);
}
}
}
}
21 changes: 21 additions & 0 deletions src/Shared/test/Shared.Tests/ArrayPoolExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.Buffers;

public sealed class ArrayPoolExtensionsTests
{
[Fact]
public void Return_PartiallyClearsArray_WithSpecifiedLengthToClear()
{
ArrayPool<int> pool = ArrayPool<int>.Create();
int[] array = pool.Rent(64);

array.AsSpan().Fill(int.MaxValue);

pool.Return(array, 42);

Assert.True(array.AsSpan(0, 42).IndexOfAnyExcept(0) < 0);
Assert.True(array.AsSpan(42).IndexOfAnyExcept(int.MaxValue) < 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
<Compile Include="$(SharedSourceRoot)Debugger\DictionaryItemDebugView.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Debugger\DictionaryDebugView.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Debugger\StringValuesDictionaryDebugView.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<Compile Include="$(SignalRSharedSourceRoot)Utf8BufferTextWriter.cs" Link="Utf8BufferTextWriter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)MemoryBufferWriter.cs" Link="MemoryBufferWriter.cs" />
<Compile Include="$(SignalRSharedSourceRoot)TryGetReturnType.cs" Link="TryGetReturnType.cs" />
<Compile Include="$(SharedSourceRoot)Buffers\ArrayPoolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

<ItemGroup>
Expand Down
14 changes: 13 additions & 1 deletion src/SignalR/common/Shared/JsonUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Buffers;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand Down Expand Up @@ -216,7 +217,18 @@ public void Return(T[]? array)
return;
}

_inner.Return(array);
#if NET
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
#else
if (!typeof(T).IsPrimitive)
#endif
{
_inner.Return(array, array.Length);
}
else
{
_inner.Return(array);
}
}
}
}
Loading