Binary operatos

What is faster :
if(x==y) //numbers are equal
or
if(!x^y) //numbers are equal

?
Any sane compiler will optimize both snippets to the same code.

But you should never write code like in your second snippet.
Martin Fowler wrote:
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.
Last edited on
Good reply.
To prove my first statement: decompiled code as on GCC 4.8.1 with -O2 optimizations:
1
2
3
4
5
6
7
8
9
__attribute__((noinline)) bool f1(int x, int y)
{
    return (x==y);
}

__attribute__((noinline)) bool f2(int x, int y)
{
    return !(x^y);
}
0x00401520	cmp    %edx,%ecx
0x00401522	sete   %al
0x00401525	retq


0x00401530	cmp    %edx,%ecx
0x00401532	sete   %al
0x00401535	retq
Same here on IBM (compiler xlc 12)

1
2
3
4
5
.f1__FiT1:
        subf       r0,r4,r3
        cntlzw     r0,r0
        rlwinm     r3,r0,27,5,31
        bclr       BO_ALWAYS,CR0_LT
.f2__FiT1:
        xor        r0,r3,r4 # okay, there is a small diff here
        cntlzw     r0,r0
        rlwinm     r3,r0,27,5,31
        bclr       BO_ALWAYS,CR0_LT

(with gcc on the same platform, it used xor for both functions)

and on a sparc: (compiler studio 12.3)

1
2
3
4
5
6
7
8
__1cCf16Fii_b_:
    xor     %o0,%o1,%o5
    srl     %o5,0,%o4
    sub     %g0,%o4,%o3
    srlx    %o3,63,%o2
    xor     %o2,1,%g5
    retl    ! Result =  %o0
    and     %g5,255,%o0
__1cCf26Fii_b_:
    xor     %o0,%o1,%o5
    srl     %o5,0,%o4
    sub     %g0,%o4,%o3
    srlx    %o3,63,%o2
    xor     %o2,1,%g5
    retl    ! Result =  %o0
    and     %g5,255,%o0
Last edited on
faster is EXAMPLE:

if(a == b)
{
//Function
}
Last edited on
Topic archived. No new replies allowed.