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
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 the
cmpinstruction, 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 as
sub, but there are many more possibilities) that sets the sign flag SF in the EFLAGS register, then there's no need for the
cmpinstruction, and the compiler can emit just a
jsinstruction. There's no simple
jCCinstruction that jumps when the input was -1.