5 ms·
The XOR swap trick is just a trick; it shouldn't be used in practice. Modern architectures can do a register swap almost for free, compared to three XORs. The b
by Xophmeister 4y ago
The XOR swap trick is just a trick; it shouldn't be used in practice. Modern architectures can do a register swap almost for free, compared to three XORs. The biggest problem is when your two values are equal: they'll get zeroed out and good luck tracking that down!
- dividuum 4y agoThat’s not correct: Equal value isn’t an issue. Having both variables point to the same memory is.
- Xophmeister 4y agoOops, my bad! I knew it was something to do with equality, but I forgot the specifics… Another good reason not to rely on tricks, I suppose!
- dividuum 4y agoAgreed. Had to think about that one too a moment, but something felt wrong. XOR is bitwise, so if your statement was true, it would mean that two 1 bits or two 0 bits would both end up producing a 0 bit result. Clearly that would make the whole thing pretty useless :)
- marginalia_nu 4y ago> The biggest problem is when your two values are equal: they'll get zeroed out and good luck tracking that down! (a,b) = (5,5) a = a ^ b # a = 0, b = 5 b = a ^ b # a = 0, b = 5 a = a ^ b # a = 5, b = 5 Hmm?
- dllthomas 4y agoAs I understand it (... haven't tested recently) you're right that it's not usually a win on modern architectures, and the compiler could do it wherever there's enough register pressure that it might actually help (if anywhere). It's still neat, but I don't think there's any reason to be writing it unless you are on a particularly constrained system with a limited compiler. I assume you're being downvoted for your slightly incorrect caveat.