Tips and Tricks #98: Leverage ArrayPool for Temporary Buffer Reuse

Rent and return arrays from a shared pool to avoid repeated allocations in buffer-heavy code.

Code Snippet

using System.Buffers;

public byte[] ProcessData(Stream stream)
{
    // Rent a buffer from the shared pool
    byte[] buffer = ArrayPool.Shared.Rent(4096);
    try
    {
        int bytesRead = stream.Read(buffer, 0, buffer.Length);
        // Process buffer...
        return ProcessBuffer(buffer, bytesRead);
    }
    finally
    {
        // Always return the buffer
        ArrayPool.Shared.Return(buffer);
    }
}

Why This Helps

  • Reuses memory instead of allocating new arrays
  • Dramatically reduces GC collections in I/O-heavy code
  • Thread-safe by design

How to Test

  • Compare Gen0/Gen1 collections before and after
  • Benchmark throughput under load

When to Use

File I/O, network operations, image processing, any scenario with frequent temporary buffers.

Performance/Security Notes

Always return buffers in a finally block. Rented arrays may be larger than requested.

References


Try this tip in your next project and share your results in the comments!


Discover more from Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.