What is faster (x < 0) or (x == -1)?

前端 未结 12 2064
栀梦
栀梦 2021-02-01 03:00

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)


        
相关标签:
12条回答
  • 2021-02-01 03: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.

    0 讨论(0)
  • 2021-02-01 03:30

    Same, both operations are usually done in 1 clock.

    0 讨论(0)
  • 2021-02-01 03:38

    As others have said there probably isn't any difference. Comparisons are such fundamental operations in a CPU that chip designers want to make them as fast as possible.

    But there is something else you could consider. Analyze the frequencies of each value and have the comparisons in that order. This could save you quite a few cycles. Of course you still need to compile your code to asm to verify this.

    0 讨论(0)
  • 2021-02-01 03:40

    I'm sure you're confident this is a real time-taker.

    I would suppose asking the machine would give a more reliable answer than any of us could give.

    I've found, even in code like you're talking about, my supposition that I knew where the time was going was not quite correct. For example, if this is in an inner loop, if there is any sort of function call, even an invisible one inserted by the compiler, the cost of that call will dominate by far.

    0 讨论(0)
  • 2021-02-01 03:41

    The important consideration, anyway, is which actually directs your program flow accurately, and which just happens to produce the same result?

    If x is actually and index or a value in an enum, then will -1 always be what you want, or will any negative value work? Right now, -1 is the only negative, but that could change.

    0 讨论(0)
  • 2021-02-01 03:43

    It depends on the architecture, but the x == -1 is more error-prone. x < 0 is the way to go.

    0 讨论(0)
提交回复
热议问题