Comparison Efficiency

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

What is generally faster:

if (num >= 10)

or:

if (!(num < 10))
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 18:17

    In general any speed difference won't matter a great deal, but they don't necessarily mean exactly the same thing.

    In many languages, comparing the floating point value NaN returns false for all comparisons, so if num = NaN, the first is false and the second true.

    #include 
    #include 
    
    int main ( ) {
        using namespace std;
    
        double num = numeric_limits::quiet_NaN();
    
        cout << boolalpha;
        cout << "( num >= 10 )      " << ( num >= 10 ) << endl;
        cout << "( ! ( num < 10 ) ) " << ( ! ( num < 10 ) ) << endl;
    
        cout << endl;
    }
    

    outputs

    ( num >= 10 )      false
    ( ! ( num < 10 ) ) true
    

    So the compiler can use a single instruction to compare num and the value 10 in the first case, but in the second may issue a second instruction to invert the result of the comparison. ( or it may just use a branch if zero rather than branch if non-zero, you can't say in general )

    Other languages and compilers will vary, and for types where they really have the same semantics the code emitted might well be identical.

提交回复
热议问题