Comparison Efficiency

后端 未结 3 519
难免孤独
难免孤独 2021-01-21 18:11

What is generally faster:

if (num >= 10)

or:

if (!(num < 10))
3条回答
  •  再見小時候
    2021-01-21 18:40

    Any decent compiler will optimize those two statements to exactly the same underlying code. In fact, it will most likely generate exactly the same code for:

    if (!(!(!(!(!(!(!(num < 10))))))))
    

    I would opt for the first of yours just because its intent seems much clearer (mildly clearer than your second choice, massively clearer than that monstrosity I posted above). I tend to think in terms of how I would read it. Think of the two sentences:

    • if number is greater than or equal to ten.
    • if it's not the case that number is less than ten.

    I believe the first one to be clearer.

    In fact, just testing with "gcc -s" to get the assembler output, both statements generate the following code:

    cmpl $9,-8(%ebp) ; compare value with 9
    jle .L3          ; branch if 9 or less.
    

    I believe you're wasting your time looking at micro-optimisations like this - you'd be far more efficient looking at things like algorithm selection. There's likely to be a much greater return on investment there.

提交回复
热议问题