Simplified algorithm for calculating remaining space in a circular buffer?

Dynite picture Dynite · Jan 16, 2009 · Viewed 7.2k times · Source

I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this?

int remaining = (end > start)
                ? end-start
                : bufferSize - start + end;

Answer

j_random_hacker picture j_random_hacker · Jan 16, 2009

If you're worried about poorly-predicted conditionals slowing down your CPU's pipeline, you could use this:

int remaining = (end - start) + (-((int) (end <= start)) & bufferSize);

But that's likely to be premature optimisation (unless you have really identified this as a hotspot). Stick with your current technique, which is much more readable.