Search code examples
c++optimizationmicro-optimization

Is x >= 0 more efficient than x > -1?


Doing a comparison in C++ with an int is x >= 0 more efficient than x > -1?


Solution

  • short answer: no.

    longer answer to provide some educational insight: it depends entirely on your compiler, allthough i bet that every sane compiler creates identical code for the 2 expressions.

    example code:

    int func_ge0(int a) {
        return a >= 0;
    }   
    
    int func_gtm1(int a) {
        return a > -1; 
    }

    and then compile and compare the resulting assembler code:

       % gcc -S -O2 -fomit-frame-pointer foo.cc
    

    yields this:

    _Z8func_ge0i:
    .LFB0:
        .cfi_startproc
        .cfi_personality 0x0,__gxx_personality_v0
        movl    4(%esp), %eax
        notl    %eax
        shrl    $31, %eax
        ret
        .cfi_endproc
    

    vs.

    _Z9func_gtm1i:
    .LFB1:
        .cfi_startproc
        .cfi_personality 0x0,__gxx_personality_v0
        movl    4(%esp), %eax
        notl    %eax
        shrl    $31, %eax
        ret
        .cfi_endproc
    

    (compiler: g++-4.4)

    conclusion: don't try to outsmart the compiler, concentrate on algorithms and data structures, benchmark and profile real bottlenecks, if in doubt: check the output of the compiler.