How to efficiently wrap the index of a fixed-size circular buffer

前端 未结 6 1015
迷失自我
迷失自我 2021-01-03 04:50

I have a fixed size circular buffer (implemented as an array): upon initialization, the buffer gets filled with the specified maximum number of elements which allows the use

6条回答
  •  一整个雨季
    2021-01-03 05:16

    I tested all 3 versions:

    // plain wrap
    public static int WrapIndex(int index, int endIndex, int maxSize)
    {
        return (endIndex + index) > maxSize ? (endIndex + index) - maxSize : endIndex + index;
    }
    
    // wrap using mod
    public static int WrapIndexMod(int index, int endIndex, int maxSize)
    {
        return (endIndex + index) % maxSize;
    }
    
    // wrap by masking out the top bits
    public static int WrapIndexMask(int index, int endIndex, int maxSize)
    {
        return (endIndex + index) & (maxSize - 1);
    }
    

    The performance results (ticks):

    Plain: 25 Mod: 16 Mask: 16 (maxSize = 512)
    Plain: 25 Mod: 17 Mask: 17 (maxSize = 1024)
    Plain: 25 Mod: 17 Mask: 17 (maxSize = 4096)
    

    So it seems that the modulus is the better choice, because it does not require any restriction on the size of the buffer.

提交回复
热议问题