Variable x is int with possible values: -1, 0, 1, 2, 3.
Which expression will be faster (in CPU ticks):
1. (x < 0)
2. (x == -1)
Language: C/C++, but I suppose all other languages will have the same.
P.S. I personally think that answer is (x < 0).
More widely for gurus: what if x from -1 to 2^30?
That depends entirely on the ISA you’re compiling for, and the quality of your compiler’s optimizer. Don’t optimize prematurely: profile first to find your bottlenecks.
That said, in x86, you’ll find that both are equally fast in most cases. In both cases, you’ll have a comparison (
cmp) and a conditional jump (jCC) instructions. However, for(x < 0), there may be some instances where the compiler can elide thecmpinstruction, speeding up your code by one whole cycle.Specifically, if the value
xis stored in a register and was recently the result of an arithmetic operation (such asadd, orsub, but there are many more possibilities) that sets the sign flag SF in the EFLAGS register, then there’s no need for thecmpinstruction, and the compiler can emit just ajsinstruction. There’s no simplejCCinstruction that jumps when the input was -1.