Hacker News new | ask | show | jobs
by jstimpfle 3477 days ago
Don't use a modulo then. Use subtraction.
1 comments

Subtraction requires a branch, which could be worse (or not) depending on architecture.
Oh, come on, you don't need a branch to do a conditional subtraction. Reify the condition to 0/1 and use multiplication, or use AND with a two's complement of the condition.
OK, my bit twiddling knowledge is weak, my google skills are weaker still, and now I'm curious: what does "AND with a two's complement of the condition" mean, exactly?
x -= N & -(x >= N);
Ohh, nice, I get it now. Thanks a lot!
Thanks! This AND trick is great. Actually makes me want to go back to assembly-level programming.
Good point!
The branch will be properly predicted every time except for when it wraps. This should be faster than any of the alternatives.
I fully believe that there are plenty of contexts where that's true - particularly in any throughput oriented system where the buffer is large. But if you care, measure.