C# › Memory & Garbage Collection
How would you use ArrayPool<T> to reduce garbage collection pressure in a high-throughput, buffer-allocating hot path?
AdvancedAnswer
ArrayPool<T>.Shared provides a pool of reusable arrays — instead of allocating a new array every time you need a temporary buffer (and letting the GC collect it shortly after), you RENT an array from the pool, use it, and RETURN it when done, dramatically reducing allocation rate and GC pressure in code that repeatedly needs similarly-sized temporary buffers.
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096); // rent instead of 'new byte[4096]'
try {
int bytesRead = stream.Read(buffer, 0, 4096);
ProcessData(buffer, bytesRead);
} finally {
ArrayPool<byte>.Shared.Return(buffer); // return it for reuse, reducing future allocations
}Real-world example Reducing GC pressure in a high-throughput network server or file-processing pipeline that constantly needs similarly-sized temporary buffers.