-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Use AllocateUninitializedArray for primitive types except bool in SharedArrayPool #121851
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
src/libraries/System.Private.CoreLib/src/System/Buffers/SharedArrayPool.cs
Outdated
Show resolved
Hide resolved
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
src/libraries/System.Private.CoreLib/src/System/Buffers/SharedArrayPool.cs
Show resolved
Hide resolved
jkotas
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR optimizes array allocation in SharedArrayPool<T> by using uninitialized arrays for primitive types (except bool) while maintaining safety for other types. Previously, all array allocations used GC.AllocateUninitializedArray, which could produce invalid bit patterns for bool and non-primitive types.
Key Changes:
- Added conditional allocation logic that uses
GC.AllocateUninitializedArray<T>()for primitive types excluding bool, andnew T[]for bool and all other types - Improves safety by ensuring bool arrays and reference/value types are properly initialized
- Maintains performance benefits of uninitialized allocation for most primitive types
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):GC.AllocateUninitializedArray<T>()for performancenew T[]for safetyConfigurableArrayPool<T>already usednew T[]and is unchangedThis 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.
Original prompt
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.