I’m having a lot of fun writing a for-fun play-money online casino these days. Every day you learn something new, and about a week ago I learned about XOR-Swap. The idea is very simple, yet very effective. The website I’m working on is written in PHP, so I’ll present the code in that language as well, but it’ll work in any language that can do eXclusive OR.
<?php a = 10; $b = 44; $a^=$b^=$a^=$b; //$a = 44; //$b = 10; ?>
If you’re having trouble reading that it might be a bit easier to write it all out.
<?php $a = 10; $b = 44; $a = $a^$b; $b = $b^$a; $a = $a^$b; //$a = 10; //$b = 44; ?>
You might be thinking; “why not do just assign a temporary variable instead“, and that works great too. However you won’t feel warm and fuzzy inside. You won’t be able to show off with your one-line ninja code either. Assigning a temporary variable and XOR-Swap is about equal in performance – I’ve benchmarked this. A temporary variable will leave a footprint equal to the size of your variable, but memory is cheap, right? However using something like list($a, $b) = array($b, $a); is a lot slower – if you think about it that makes sense as you actually have to populate the array before assigning it to the variables in the list. When I say a lot slower, I mean a lot slower. I might post benchmarks for this in a later post.
One thing you have to worry about is if the the two variables you’re XOR-Swapping are not the same type or if they are of unequal length. XOR-Swapping $a = "hello"; $b = "world"; will work, but $a = "hello"; $b = "world!"; will break.