Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 485
gerarddp Avatar asked Nov 29 '11 19:11

gerarddp


People also ask

Is x ++ or x 1 more efficient?

Which is faster? ++, += or x + 1? The bottom line is that in most but not all languages the compiler is going to make them identical anyway, so there's no difference in efficiency.

What is the --> operator in C C ++?

The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Operation: The -> operator in C or C++ gives the value held by variable_name to structure or union variable pointer_name.

Which one will be faster or != Why?

C. != is much faster. Anything with an exclamation point is given top priority in the Oracle engine.


1 Answers

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.

like image 167
akira Avatar answered Oct 10 '22 06:10

akira