Wednesday, March 16, 2011

Faster Swap - XOR or Temporary Variable?

Jerry Pisk asks -- Which is faster for swapping integer values – the old XOR “trick” or just using a temp variable? 

Jerry opines that the temp var method should be faster - I agreed, but thought it might be interesting to dig into this a little.

There’s a fair amount of anecdotal evidence on the internets about this topic already, but I wanted to test the theory out in both C# and in C++ (MSVC) for myself.

The algorithm I used to compare went like this: create two large-ish arrays, fill them with random, unsigned 32-bit ints and then reverse the arrays in place – one using temp storage and the other using XOR.

The crux of the code looks like this:

Swap
          while (i < j) {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
           }
 
XOR
          while (i < j) {
                array[i] ^= array[j];
                array[j] ^= array[i];
                array[i] ^= array[j];
            }

My mean timings over a few thousand iterations were identical for both languages on my machine – ~11ms for Temp and ~17ms for XOR for 5 million swap operations.

I was interested to see what the compilers did to the high-level XORs and, in the end, they did essentially the same thing:

.Net
xor   dword ptr [edx],eax

C++

xor    DWORD PTR [eax+edx*4], esi

Note: I didn’t see the XCHG instruction in either language for either algorithm.

So we see that the temp variable swap technique is significantly faster than the XOR swap technique (in these languages on my machine, etc.).

Wednesday, March 2, 2011

Some HTML5 Fun

I’ve been playing around with HTML5 and with the <canvas> tag in particular. It’s pretty neat – especially how quickly you can put something together.

I’d been looking at Conway's Game of Life and thought it’d be a fun way to dig into something slightly more complex than just drawing lines on the canvas tag (boring! :).

I pretty quickly had something up and running and found the game fun to watch. I chose to use a random start state, but this could be easily tweaked to use some of the well-known start states which produce cool effects (see the Wikipedia article for some of those).

I’m planning on Open Sourcing it shortly (it’s nothing awesome, but I thought I’d share it anyway).

Here’s a screen shot of it “in action”:



 I'll follow up shortly with its new home.