What is faster (x < 0) or (x ==
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.
PS 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 the cmp
instruction, speeding up your code by one whole cycle.
Specifically, if the value x
is stored in a register and was recently the result of an arithmetic operation (such as add
, or sub
, but there are many more possibilities) that sets the sign flag SF in the EFLAGS register, then there's no need for the cmp
instruction, and the compiler can emit just a js
instruction. There's no simple jCC
instruction that jumps when the input was -1.
Why? Whichever you do, the compiler will optimize it on whatever platform you are currently compiling on.
If you need to check if it's -1, use (x == -1), if you want to know if it's less than zero, use that one instead. Write what you would read out loud.
Tiny things like this won't make anything faster, and you should be worried about readability and clean design rather than which tiny operation is faster.
And even if it doesn't do any logical changes, chances are on your platform, both will perform in one CPU cycle .
Try it and see! Do a million, or better, a billion of each and time them. I bet there is no statistical significance in your results, but who knows -- maybe on your platform and compiler, you might find a result.
This is a great experiment to convince yourself that premature optimization is probably not worth your time--and may well be "the root of all evil--at least in programming".
链接地址: http://www.djcxy.com/p/31558.html上一篇: 1 vs x> = 0,是否有性能差异
下一篇: 什么是更快(x <0)或(x ==