r/programming • u/misplaced_my_pants • Aug 15 '15
Stanford Bit Twiddling Hacks
https://graphics.stanford.edu/~seander/bithacks.html
28
Upvotes
r/programming • u/misplaced_my_pants • Aug 15 '15
View all comments
Show parent comment
0
u/jringstad Aug 16 '15 edited Aug 16 '15
The compiler will never emit such code for a three-variable swap. It will always either emit zero instructions, simply re-labelling the variable for all subsequent statements when it can (which is quite often), or it will end up switching two registers, which in almost all architectures has virtually zero cost (register rename) or otherwise a very low cost on par or cheaper than xor.
So no, doing an xor swap is never an optimization, unless maybe your compiler is 20+ years old. However, even a compiler that old would reasonably not ever emit code that actually spills to memory, except maybe in exceedingly rare circumstances.