Comparison Efficiency

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

What is generally faster:

if (num >= 10)

or:

if (!(num < 10))
3条回答
  •  孤城傲影
    2021-01-21 18:21

    The compiler will most likely optimize that sort of thing. Don't worry about it, just code for clarity in this case.

    Assembly languages often have operations for >= and <= that are the same number of steps as < and >. For instance, with a Motorola 68k, if you want to compare the data registers %d0 and %d1 and branch if %d0 is greater than or equal to %d1, you would say something like:

    cmp %d0, %d1  // compare %d0 and %d1, storing the result
                  // in the condition code registers.
    bge labelname // Branch to the given label name if the comparison
                  // yielded "greater than or equal to" (hence bge)
    

    It's a common mistake to think that a >= b means the computer will perform two operations instead of one because of that "or" in "greater than or equal to".

提交回复
热议问题