DEV Community

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

Collapse
 
theoutlander profile image
Nick Karnik

The swap with bitwise operators will be the fastest at the hardware level. :)

Collapse
 
sadarshannaiynar profile image
Adarsh

Yes. Whenever you can achieve something using bitwise operations I always prefer that.

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.

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

When I started going through the comments, I was actually thinking "what about bitwise xor?" And sure enough, here it is. ^,^