Buffer allocation strategiesA possible solution

time to read 3 min | 427 words

After my recent posts about allocations, I thought that I would present a possible solution for buffer management.

The idea is to have a good way to manage buffers for things like I/O operations, etc. Here is the code:

    [ThreadStatic] private static Stack<byte[]>[] _buffersBySize;

    private static byte[] GetBuffer(int requestedSize)
    {
        if(_buffersBySize == null)
            _buffersBySize = new Stack<byte[]>[32];

        var actualSize = PowerOfTwo(requestedSize);
        var pos = MostSignificantBit(actualSize);

        if(_buffersBySize[pos] == null)
            _buffersBySize[pos] = new Stack<byte[]>();

        if(_buffersBySize[pos].Count == 0)
            return new byte[actualSize];

        return _buffersBySize[pos].Pop();
    }

    private static void ReturnBuffer(byte[] buffer)
    {
        var actualSize = PowerOfTwo(buffer.Length);
        if(actualSize != buffer.Length)
            return; // can't put a buffer of strange size here (probably an error)

        if(_buffersBySize == null)
            _buffersBySize = new Stack<byte[]>[32];

        var pos = MostSignificantBit(actualSize);

        if(_buffersBySize[pos] == null)
            _buffersBySize[pos] = new Stack<byte[]>();


        _buffersBySize[pos].Push(buffer);
    }

I’m going to discuss it in my next post, but for now, can you figure out what it is doing, and what are the implications?

More posts in "Buffer allocation strategies" series:

  1. (09 Sep 2015) Bad usage patterns
  2. (08 Sep 2015) Explaining the solution
  3. (07 Sep 2015) A possible solution