2010/10/16

Swap Two Integer Variables

//Following function utilize XCHG instruction to swap two
//DWORD variables. Since no temporary memory and stack
//is utilized (swapping is done within registers and internal
//processor cache), this routine deliver fastest swapping
//speed possible using classic 32 bits x86 instruction set.

procedure SwapInt(var i1,i2: Integer); assembler; register;
asm
mov ecx, [eax] xchg ecx, [edx] mov [eax], ecx
end;

Note: this routine destroy ECX register. If somehow you need to preserve ECX, instead of push/pop-ing it from stack, replace two MOV instructions above with XCHG instructions.

No comments:

Post a Comment