c# using bitwise XOR for swapping

前端 未结 7 1535
借酒劲吻你
借酒劲吻你 2020-12-18 12:40
void swap(ref int x, ref int y)
{       x = x ^ y;   y = y ^ x;   x = x ^ y;  }

im learning about bitwise XOR. how is this swapping occurring? it\'

7条回答
  •  旧时难觅i
    2020-12-18 13:07

    swap() can be implemented with a single CPU instruction on most modern architectures (including i686 and x86_64). Hence, you are better off writing it in a way the compiler can recognize and convert accordingly rather than trying to micro optimize in a way that will actually make your code slower and less readable.

提交回复
热议问题