How to efficiently wrap a fixed-size circular buffer index

I have a fixed-size ring buffer (implemented as an array): upon initialization, the buffer is filled with the specified maximum number of elements, which allows us to use one position index to track our current position in a circle.

What is an efficient way to access an element in a ring buffer? Here is my current solution:

int GetElement(int index)
{
    if (index >= buffer_size || index < 0)
    {
        // some code to handle the case
    }
    else
    {
        // wrap the index
        index = end_index + index >= buffer_size ? (index + end_index) - buffer_size : end_index + index;
    }

    return buffer[index];
}

Some definitions:
end_indexis the index of the element immediately after the last element in the circle (it will also be considered the same as start_index or the first element of the circle).
buffer_size- maximum buffer size.

+5
source share
6

, .

+10

, , :

public static int Wrap(int index, int n)
{
    return ((index % n) + n) % n;
}

(, )

+11

, , , - return (end_index + index) % buffer_size;

+5

3 :

// 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);
}

():

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

, , , .

+4
int GetElement(int index)
{
    return buffer[(end_index + index) % buffer_size];
}

< modulo (%).

+3

FWIW, : i = next[i];

, , : i++; if (i >= n) i = 0; i = (i+1) % n;

Despite this, I would be very surprised if this is ever a significant performance issue.

0
source

All Articles