Skip to content

Commit 73c8ac2

Browse files
Copilotstephentoub
andauthored
Use AllocateUninitializedArray for primitive types except bool in SharedArrayPool (#121851)
ArrayPool now uses a conditional allocation strategy to balance performance and safety. Primitive types (excluding bool) use uninitialized arrays for better performance, while bool and non-primitive types use initialized arrays. ### Changes - `SharedArrayPool<T>.Rent()`: Changed to use conditional allocation (lines 110-112): - **Primitive types (excluding bool)**: Uses `GC.AllocateUninitializedArray<T>()` for performance - **bool and non-primitive types**: Uses `new T[]` for safety - `ConfigurableArrayPool<T>` already used `new T[]` and is unchanged This approach optimizes performance for primitive types where any bit pattern is valid, while ensuring proper initialization for bool (which has problematic bit patterns) and all reference/value types. <!-- START COPILOT CODING AGENT SUFFIX --> <details> <summary>Original prompt</summary> > ArrayPool currently uses GetUninitializedArray. This makes some array allocations faster, but arrays should only be allocated rarely. Please switch it to just using new T[]. </details> <!-- START COPILOT CODING AGENT TIPS --> --- ✨ Let Copilot coding agent [set things up for you](https://github.com/dotnet/runtime/issues/new?title=✨+Set+up+Copilot+instructions&body=Configure%20instructions%20for%20this%20repository%20as%20documented%20in%20%5BBest%20practices%20for%20Copilot%20coding%20agent%20in%20your%20repository%5D%28https://gh.io/copilot-coding-agent-tips%29%2E%0A%0A%3COnboard%20this%20repo%3E&assignees=copilot) — coding agent works faster and does higher quality work when set up for your repo. --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: stephentoub <[email protected]> Co-authored-by: Stephen Toub <[email protected]>
1 parent c8675d9 commit 73c8ac2

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/libraries/System.Private.CoreLib/src/System/Buffers/SharedArrayPool.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,13 @@ public override T[] Rent(int minimumLength)
107107
ArgumentOutOfRangeException.ThrowIfNegative(minimumLength);
108108
}
109109

110-
buffer = GC.AllocateUninitializedArray<T>(minimumLength);
110+
// For large arrays, we prefer to avoid the zero-initialization costs. However, as the resulting
111+
// arrays could end up containing arbitrary bit patterns, we only allow this for types for which
112+
// every possible bit pattern is valid.
113+
buffer = typeof(T).IsPrimitive && typeof(T) != typeof(bool) ?
114+
GC.AllocateUninitializedArray<T>(minimumLength) :
115+
new T[minimumLength];
116+
111117
if (log.IsEnabled())
112118
{
113119
int bufferId = buffer.GetHashCode();

0 commit comments

Comments
 (0)