Function 1: naiveSwap
Function 2: xorSwap
Function 3: addSwap
Summary:
naiveSwap | xorSwap | addSwap | |
extra variable | need | not need | not need |
check \(x \ne y\) (address) | not need | need | need |
readability | good | not good | not good |
overflow | no problem | no problem | potential problem |
aliasing | fine | complicated | complicated |
execution model | instruction pipeline | strictly sequential | strictly sequential |
Situations for XOR use in practice:
- On a processor where the instruction set encoding permits the XOR swap to be encoded in a smaller number of bytes;
- In a region with high register pressure, it may allow the register allocator to avoid spilling a register;
- In Microcontrollers where available RAM is very limited.
Because of the problem of overflow, the add-swap approach is used less often.
References:
Wikipedia item: XOR swap algorithm
No comments:
Post a Comment