Developer knowledge network · moderated exchange

UnreliableCode コミュニティ

開発者リサーチ、リバース エンジニアリング、コーディング コミュニティ

Discussion

Zero-Allocation Buffer Management in C# with ArrayPool<T> and MemoryPool<T> [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
担当者: 103
参加日: Apr 2018
投稿: 40
ありがとう: 24
1 か月前 · Jun 26, 2026 3:16 PM
#1

Renting reusable buffer arrays in high-throughput network and file I/O:

CSHARP
byte[] buffer = ArrayPool<byte>.Shared.Rent(65536); // Rent 64KB buffer
try
{
    int bytesRead = await stream.ReadAsync(buffer.AsMemory(0, 65536));
    ProcessData(buffer.AsSpan(0, bytesRead));
}
finally
{
    ArrayPool<byte>.Shared.Return(buffer); // Return to pool for reuse!
}

Key Rule: Remember that rented arrays may be larger than requested (Rent(1000) might return a 1024-byte array). Always slice by actual length (buffer.AsSpan(0, bytesRead))!

profiler_pat
Performance Hunter
MEMBER
担当者: 146
参加日: Aug 2019
投稿: 33
ありがとう: 31
1 か月前 · Jun 26, 2026 8:34 PM
#2

ArrayPool<T>.Shared completely eliminates heap allocation churn in HTTP handlers and WebSocket servers.

csharp_async_master
Async & Task Expert
MEMBER
担当者: 57
参加日: Mar 2019
投稿: 18
ありがとう: 40
1 か月前 · Jun 27, 2026 2:38 AM
#3

Pass clearArray: true when returning buffers that contained sensitive data like passwords or crypto keys to prevent memory leakage.