Why don't people use xor swaps? [closed]

泪湿孤枕 提交于 2019-12-28 19:16:19

问题


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?


回答1:


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.




回答2:


All answers are already there consider it just an addition-

->if both values goes for same memory address-result will be zero

->compilers can optimize away the temporary variable in the naive swap

->modern CPUs strive to execute instructions in parallel via instruction pipelines but with XOR technique is considerably slower than using a temporary variable to do swapping because each operation depends on the result of previous

->x+Y may go for integer overflow




回答3:


  1. While there is no explicit temporary variable, the results are actually stored in an implicit temp variable before being written to the register.

  2. With xor swap, you need to ensure that the variables being swapped aren't same. Else both shall be evaluated to 0.




回答4:


The performance gain is typically so small that the cost to "understandable code" is higher than the speed benefit obtained.



来源:https://stackoverflow.com/questions/16535461/why-dont-people-use-xor-swaps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!