HeadlinesBriefing favicon HeadlinesBriefing.com

When to Use .NET ArrayPool Wisely

DEV Community •
×

Pooling lets .NET developers recycle expensive objects instead of repeatedly allocating them. The framework ships only a few built‑in pools, most notably ThreadPool and ArrayPool, each with distinct trade‑offs. When applied judiciously, reuse can shave latency; applied blindly, it adds complexity and can even hurt performance. For custom strategies, the Microsoft.Extensions.ObjectPool package offers a solid template.

Typical usage calls ArrayPool.Shared.Rent(desiredLength) and later ArrayPool.Shared.Return(buffer, clearArray:true) inside a finally block. The pool rounds requests to the nearest power of two, so renting 20 bytes often yields a 32‑byte array. Because returned buffers are not zeroed, stale data can leak into subsequent reads, and reference‑type elements may prevent garbage collection, creating subtle memory‑leak scenarios.

Guidelines advise avoiding ArrayPool for buffers smaller than 16 bytes, where the GC or stack allocation is cheaper. Never expose a rented array beyond the method that rented it; returning it later becomes unreliable and may trigger exceptions. Profiling remains the safest way to confirm a net gain, and upcoming .NET releases may introduce automatic clearing options to simplify usage.