cswapxorpremature-optimization

Why don't people use xor swaps?


I read on a site that using xor swaps is fast because it doesn't use a temporary variable. Here's an example:

#include <stdio.h>

int main(void)
{        
    int a=234,b=789;
    b=b^a;
    a=b^a;
    b=b^a;
    printf("a=%d,b=%d",a,b);
    return 0;
}

Why don't people use this technique in real life code? Is it just poor style? Is there something not well defined about it? Is it an optimisation that my compiler might produce from more clear code, automatically?


Solution

  • Using a tmp variable is both faster and more readable with modern compilers and CPUs. 2x loads into registers, then 2x stores back into the original locations.

    Or if one or both variables were already in registers, the compiler might completely optimize anyway the temporary. If xor-swapping was faster on some hypothetical machine, a good compiler would use it for you when optimizing tmp = a; a = b; b = tmp; So you don't need to write it explicitly. This is why you're using C, not writing by hand in asm.

    Also, xor-swap works for integers only. What if you want to swap floating-point numbers? Strings? Custom objects? etc.