C# › Memory & Garbage Collection

How would you use ArrayPool<T> to reduce garbage collection pressure in a high-throughput, buffer-allocating hot path?

Advanced

Answer

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.

Common follow-ups: Why must you be careful about the RETURNED array's contents, given ArrayPool doesn't automatically clear it by default?