Cryptic code == Optimized code ? YES : NO ;

Jon C. R. Bennett jb7m+ at andrew.cmu.edu
Thu Sep 13 11:15:09 AEST 1990


scjones at thor.UUCP (Larry Jones) writes:

> ... The common swap code:
>         tmp = a;  a = b;  b = a;
> is not only more obvious, but probably faster as well.

It IS faster.

> 
> >    Example 3: Variables a and b are of the same type either int , char
> >        a )     a = a ^ b;  b = a ^ b;  a = a ^ b;
> >        b )     a = a ^ ( b = b ^ ( a = a ^ b ));
> >        c )     a ^= b ^= a ^= b;
> 

I have had it with this "lets swap using xor" stuff, on machines with lots
of registers (like the MIPS R2000 I'm about to use as an example) you are
far better of with  
"tmp = a;  a = b;  b = a;" then  
a = a ^ b;  b = a ^b;  a = a ^ b; 

below are two functions followed by the optimized assembly output

int bar(a,b)
 int a,b;
{
    int tmp;

    a ^= b;    b ^= a;    a ^= b;
    return a+b;
}
	bar:
  [foo.c:  18] 0x10:	00852026	xor	r4,r4,r5
  [foo.c:  19] 0x14:	00a42826	xor	r5,r5,r4
  [foo.c:  20] 0x18:	00852026	xor	r4,r4,r5
  [foo.c:  22] 0x1c:	03e00008	jr	r31
  [foo.c:  22] 0x20:	00851021	addu	r2,r4,r5


int foo(a,b)
 int a,b;
{
    int tmp;

    tmp= a;   a = b;    b=tmp;
    return a+b;
}
	foo:
  [foo.c:   6] 0x0:	00801821	move	r3,r4
  [foo.c:   7] 0x4:	00a02021	move	r4,r5
  [foo.c:  10] 0x8:	03e00008	jr	r31
  [foo.c:  10] 0xc:	00831021	addu	r2,r4,r3

not only is the obvious code easier to read, it is faster, any good
compiler (like GCC or the MIPS compiler) will seee that "tmp" becomes a
dead variable and not bother to move it, generating faster code. Since the
"xor swap" is harder to read, and slower, there is no good reason to not
just swap the varibles in the obvious way as opposed to using the "clever"
but worse (to read and to compile) xor hack.

 please stop

jon bennett



More information about the Comp.lang.c mailing list