3y ago · Apr 12, 2023 11:20 AM
Hey guys! I wanted to write a quick guide on using in high-throughput network and file I/O services.
1. The Core Benefit:
Instead of allocating a new on every incoming packet and triggering Gen0 GC sweeps, you rent a pre-allocated array from the shared pool:
2. Two Big Gotchas to Watch Out For:
- Rented arrays can be larger than requested: might return an array of length 8192! Always track your actual count and use , never .
- clearArray Parameter: Set if the buffer contained sensitive user passwords or tokens so subsequent renters cannot read stale memory!
CODE
ArrayPool<T>.Shared1. The Core Benefit:
Instead of allocating a new
CODE
new byte[4096] CSHARP
byte[] buffer = ArrayPool<byte>.Shared.Rent(minimumLength: 4096);
try
{
int bytesRead = await stream.ReadAsync(buffer.AsMemory(0, 4096), cancellationToken);
ProcessPacket(buffer.AsSpan(0, bytesRead));
}
finally
{
// Always return in a finally block!
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}2. Two Big Gotchas to Watch Out For:
- Rented arrays can be larger than requested:
CODE
Rent(4096) CODE
bytesRead CODE
buffer.AsSpan(0, count) CODE
buffer.Length- clearArray Parameter: Set
CODE
clearArray: true
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: