Swapping values in C#:
Tmp variable vs. XOR with performance times.

While doing a bit of coding for an upcoming post (probably the one following this) I was doing a variable swap. I started with a temporary variable swap but then decided to be cute and implement an XOR swap. As a benefit, I had the chance to remind myself how to do this (without cheating). However, I ran into an issue when I wanted to create a generalize swap function. Researching the issue, I came upon a post about how the XOR swap is not as efficient in modern architecture. Surprising! Dot Net Perls has a page about it with a link to the Wikipedia article.

As a reminder, an XOR swap can be achieved by doing the following on two variables:

int x = 1;
int y = 2;

x ^= y;
y ^= x;
x ^= y;

Console.WriteLine("x = {0}", x);
Console.WriteLine("y = {0}", y);


x = 2
y = 1

Below is the code I used to check the performance of the two methods.

int[] numbers = { 1, 2 };
int iterations = 100000000;		//Number of swap iterations
var timer = new Stopwatch();

//	XOR Swap Test
for (int i = 0; i < iterations; ++i) {
	numbers[0] ^= numbers[1];
	numbers[1] ^= numbers[0];
	numbers[0] ^= numbers[1];

Console.WriteLine("XOR Swap time: {0}", timer.Elapsed);


//	Temporary Variable Swap Test
for (int i = 0; i < iterations; ++i) {
	int tmp = numbers[0];
	numbers[0] = numbers[1];
	numbers[1] = tmp;

Console.WriteLine("Temp Variable Swap time: {0}", timer.Elapsed);

Here is sample output of a few runs:

XOR Swap time: 00:00:01.1918037
Temp Variable Swap time: 00:00:00.6617117

XOR Swap time: 00:00:01.1561061
Temp Variable Swap time: 00:00:00.6587373

XOR Swap time: 00:00:01.1674577
Temp Variable Swap time: 00:00:00.6651171

Of course these times vary a bit with the number of iterations and what else your computer is doing when it’s run, but I never saw the XOR swap performance beat the temporary variable. Who says bit manipulation is always faster?