2y ago · Apr 16, 2024 11:40 AM
Whenever you allocate a new array , 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:
Benchmark Result: On large buffers (>64KB), skipping the zeroing pass is **3x to 5x faster** on memory allocation!
CODE
new byte[65536]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...
Zero-allocation C# code using Span<T>, Memory<T>, and Unsafe...
The following users thanked BytePusher for this post: