`ArrayPool<T>` & `MemoryPool<T>`: Reusable Buffer Pooling
1Concept
`ArrayPool<T>.Shared` rents reusable heap arrays from a thread-safe shared pool. Returning arrays after use reduces Garbage Collection Gen 0/1/2 pauses to near zero in high-throughput APIs.
2Architecture Diagram
ArrayPool<T>.Shared.Rent(4096) ──> Leases pre-allocated 4KB buffer from pool
│
▼ (Process request)
ArrayPool<T>.Shared.Return(buffer) ──> Returns buffer back to pool (Zero GC Allocations!)3Code Example
C# 13 & .NET 9
using System;
using System.Buffers;
public class ArrayPoolDemo
{
public static void Main()
{
// Rent buffer of at least 1024 elements
int[] buffer = ArrayPool<int>.Shared.Rent(1024);
try
{
buffer[0] = 100;
buffer[1] = 200;
Console.WriteLine($"Rented buffer actual length: {buffer.Length} elements");
}
finally
{
// ClearArray: false for speed unless containing sensitive data
ArrayPool<int>.Shared.Return(buffer, clearArray: false);
Console.WriteLine("Buffer returned to ArrayPool.Shared cleanly.");
}
}
}4Expected Output
Rented buffer actual length: 1024 elements Buffer returned to ArrayPool.Shared cleanly.
5Key Takeaways
- ✓Always wrap rented arrays in `try-finally` to ensure they are returned.
- ✓Rented arrays may be larger than the requested size; use the requested length or Span slice.
- ✓Set `clearArray: true` when storing confidential data (passwords, tokens).