The XOR swap algorithm is an old programming trick. I’ve never personally seriously entertained using it, even in C, but myths abound that it is somehow faster than simple swapping via a temporary variable. Is it fast or just fancy?

As usual, I’ve put together a simple test to see if using XOR swap is any faster. Here it is:

package
{
	import flash.display.*;
	import flash.utils.*;
	import flash.text.*;
 
	public class XORSwapTest extends Sprite
	{
		public function XORSwapTest()
		{
			var logger:TextField = new TextField();
			logger.autoSize = TextFieldAutoSize.LEFT;
			addChild(logger);
 
			var i:int;
 
			// XOR swap is NOT faster and only works for integers
			const SWAP_REPS:int = 100000000;
			var a:int = 5;
			var b:int = 6;
			var temp:int;
			var beforeTime:int = getTimer();
			for (i = 0; i < SWAP_REPS; ++i)
			{
				temp = a;
				a = b;
				b = temp;
			}
			logger.appendText("Assign swap time: " + (getTimer()-beforeTime) + "\n");
			beforeTime = getTimer();
			for (i = 0; i < SWAP_REPS; ++i)
			{
				a ^= b;
				b ^= a;
				a ^= b;
			}
			logger.appendText("XOR swap time: " + (getTimer()-beforeTime));
		}
	}
}

And here are the results I got:

Machine Assign Swap Time XOR Swap Time
3.0 Ghz Intel Core 2 Duo with 2GB RAM on Windows XP 236 276
2.2 Ghz Intel Core 2 Duo with 2GB RAM on Mac OS X 10.6 321 368

At least in the case of AS3 on Flash Player 10, XOR swap is always slower than a regular swap via the assignment operator. Not only is the XOR swap slower, but it also only works with integers and is therefore less flexible and is an obscure technique so is less readable by others. So if you see anyone using a XOR swap in their AS3 code, kindly point them to this article. Of course, you should probably first remove any XOR swaps of your own!