Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
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.