Home / Forums / High-Performance Uninitialized Array Allocation with GC.AllocateUninitializedArray<T>

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

High-Performance Uninitialized Array Allocation with GC.AllocateUninitializedArray<T>

BytePusher
Memory & Performance
MEMBER
Rep: 209
Join Date: Dec 2025
Posts: 13
Thanks: 32
2y ago · Apr 16, 2024 11:40 AM
#1
Whenever you allocate a new array
CODE
new byte[65536]
, the CLR automatically zeros out all 65,536 bytes of memory for memory safety.

If you are about to immediately overwrite the entire array from a network socket or file read anyway, zeroing the memory is pure wasted CPU cycles!

Using
CODE
GC.AllocateUninitializedArray<T>
:

CSHARP
// Allocates array without zeroing memory!
byte[] rawBuffer = GC.AllocateUninitializedArray<byte>(length: 65536, pinned: false);

// Immediately fill buffer from socket/stream
await fileStream.ReadExactlyAsync(rawBuffer, 0, rawBuffer.Length);


Benchmark Result: On large buffers (>64KB), skipping the zeroing pass is **3x to 5x faster** on memory allocation!
BytePusher · Memory & Performance
Zero-allocation C# code using Span<T>, Memory<T>, and Unsafe...
The following users thanked BytePusher for this post:
GarbageCollector
CLR Internals
MEMBER
Rep: 255
Join Date: Oct 2023
Posts: 7
Thanks: 50
2y ago · Apr 16, 2024 12:57 PM
#2
Great optimization for cryptographic buffers and image decoding! Just remember: only use this for primitive value types (byte, int, float, structs). You cannot allocate uninitialized arrays of managed reference types (classes/strings) because the GC requires valid object references.
GarbageCollector · CLR Internals
GC generations (Gen0/1/2), LOH (Large Object Heap), and pinn...
ThreadRacer
High Performance C++
VIP
Rep: 71
Join Date: Apr 2023
Posts: 9
Thanks: 17
2y ago · Apr 16, 2024 2:57 PM
#3
The
CODE
pinned: true
parameter is also handy if you need to pass the buffer directly to a native C++ DLL or Win32 API without creating a
CODE
GCHandle
pin!
ThreadRacer · High Performance C++
Lock-free SPSC/MPMC queues, atomic memory orders, and low-la...