DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
almostconverge profile image
Peter Ellis

Rather disappointingly, in most modern hardware it's the one with the temp variable that is fastest.

Thread Thread
 
theoutlander profile image
Nick Karnik

Depending on the architecture and compiler, they end up using three registers to do a swap under the hood I think.

Thread Thread
 
almostconverge profile image
Peter Ellis

Yes, but the idea is that you do this in assembly. It was a common trick because it saved a register and (at worst) it ran in the same number of cycles.