Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!emory!mephisto!udel!rochester!pt.cs.cmu.edu!o.gp.cs.cmu.edu!andrew.cmu.edu!jb7m+ From: jb7m+@andrew.cmu.edu (Jon C. R. Bennett) Newsgroups: comp.lang.c Subject: Re: Cryptic code == Optimized code ? YES : NO ; Message-ID: Date: 13 Sep 90 01:15:09 GMT References: <861@gtenmc.UUCP>, <168@thor.UUCP> Organization: Carnegie Institute of Technology, Carnegie Mellon, Pittsburgh, PA Lines: 64 In-Reply-To: <168@thor.UUCP> scjones@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