I thought I’d share a little trick I learnt the other day regarding swapping variables.
A common coding/computer science task is to swap the values of two variables. In some languages, such as Java, one may start by creating a new temporary variable. For example (assuming we already have two ints, x and y):
int temp = x;
x = y;
y = temp;
This creation of a new variable uses more memory, and whilst in most circumstances would be fine, it could become an issue if we’re swapping many times, for example in a sorting algorithm.
Some languages allow us to do a nice swap without extra variables, using multiple assignment and tuple packing and unpacking:
x, y = y, x
This is pretty neat, although is apparently slower than using a temporary variable.
Anyway, yesterday I discovered a third method: XOR swapping. Again, this doesn’t require the use of an extra variable, and I thought it was pretty clever (here ^ represents XOR, as in Python):
x = x ^ y
y = x ^ y
x = x ^ y
Neat, huh? It’s fairly simple to see how it works if you simply walk through the steps. Let’s swap x = 7, y = 9:
x = 0111
y = 1001
x = x ^ y = 1110
y = x ^ y = 0111
x = x ^ y = 1001
Apparently this method is quite commonly used in embedded assembly code, however you won’t find it appearing much in code on a desktop computer. It usually is slower to compute than using temporary variables, as most processors attempt to execute commands in parallel – and of course, each of these instructions depends upon the previous result, so they must be executed sequentially. Still, it’s a nice thing to know.
The short version: it seems that if you’re trying to save memory then XOR swap or use multiple assignment, otherwise if efficiency is an issue, use a temporary variable.