Pools
For scenarios that create many temporary writable buffers (for example when encoding messages), the library provides buffer pools.
Pools allow buffers to reuse underlying byte[] instances, reducing allocations and GC pressure in high-throughput environments.
Two pool implementations are available:
ByteBufferPoolTrackedByteBufferPool
ByteBufferPool
ByteBufferPool rents writable buffers backed by reusable byte[] arrays.
Creating a ByteBufferPool instance is inexpensive and does not allocate any buffers by itself. The pool simply acts as a host for rented buffers.
Because of this, it is safe to either:
- Create pool instances as needed, or
- Keep a shared singleton instance
Both approaches behave the same from a memory and performance perspective.
Example:
var pool = new ByteBufferPool();
using var buffer = pool.Rent();
buffer.WriteInt32( 123 );
buffer.WriteByte( 1 );
var readable = buffer.AsReadableView();
The buffer behaves exactly like a regular WritableByteBuffer.
If more capacity is required while writing, the buffer will automatically grow as needed.
When this happens:
- The previous array is returned to the pool
- A larger array is rented
When the buffer is disposed:
- The underlying array is returned to the pool
- The buffer instance becomes unusable
Important
Buffers rented from a pool must be disposed when no longer needed so the underlying array can be returned to the pool.
TrackedByteBufferPool
TrackedByteBufferPool builds on top of ByteBufferPool and tracks all buffers rented within its scope.
When the pool is disposed, any buffers that were not manually disposed are automatically released.
Example:
using var pool = new TrackedByteBufferPool();
var buffer1 = pool.Rent();
var buffer2 = pool.Rent();
buffer1.WriteInt32( 123 );
// disposing the pool automatically disposes any remaining buffers
This is useful when multiple buffers are created within the same logical scope and should all be released together. Instead of disposing each buffer individually, disposing the pool will release any remaining rented buffers automatically.
Tip
Rented buffers can still be disposed manually. If so, they are automatically removed from the tracked set.