3 ms·
My favorite way is using the xor operator: a = a ^ b b = a ^ b a = a ^ b The above syntax works well in Python, but of course Python also had the much simpl
by falcor84 7y ago
My favorite way is using the xor operator:
a = a ^ b
b = a ^ b
a = a ^ b
The above syntax works well in Python, but of course Python also had the much simpler tuple unpacking:
a, b = b, a
- soVeryTired 7y agoIf I ever saw the xor trick in a workplace environment I'd flip out. Python's tuple unpacking is fair enough, but whatever happened to good old tmp = a, a = b, b = tmp?
- quicklime 7y agoThe XOR trick looks cool, but requires three CPU instructions to execute. My favorite way to swap variables is to use: tmp = a; a = b; b = tmp When a compiler generates code, it maintains a mapping from variables to registers. So when the source code refers to the variable 'a', the compiler might map this to register %eax, and 'b' to %ebx, and it will use this to generate assembly code (or IR or bytecode or whatever). A good compiler will recognize the three-line variable swap above, and optimize it so that the mapping simply changes at that point. So any references to the variable 'a' before the swap will refer to %eax, and after will refer to %ebx. This requires zero instructions, and zero is less than three :)
- JoshTriplett 7y agoThat doesn't necessarily work if you're doing the operation in a loop, unless the compiler also unrolls the loop to some degree (which isn't a zero-instruction change). It also only applies to local variables, and doesn't apply when swapping global or in-memory data. I've rarely encountered a "swap" operation on local variables in straight-line code, as opposed to a loop, or a swap of global/in-memory values.