Monday, May 05, 2008

A Question of Two Exchanges

Let me interrupt the functional programming 101 series to pose an interesting question.

Question: Which of these two methods of swapping a list of integers is faster?

Method 1: Plain C Code
for(int i = 0; i <  array_size; i++)
{
    int temp = a[i];
    a[i] = b[i];
    b[i] = temp;
}

Method 2: Inline Assembly using the XCHG instruction.
__asm
{
    mov ecx, array_size;
    mov esi, a;
    mov edi, b;

loopstart:
    mov eax, [esi];
    xchg [edi], eax;
    mov [esi], eax;

    add esi, 4;
    add edi, 4;
    sub ecx, 1;
    jnz loopstart;
}
(Vague?) Hint: The Intel engineers who designed the XCHG instruction decided that it would primarily be used to implement synchronization primitives like semaphores and mutexes.

Comment to let me know what you're thinking about the two snippets of code and why any one of the two should be faster or slower than the other. In my next entry I will post the answer and also dig deeper in the mechanics of the exchanges.

0 comments: