Code Snippets
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Home :: Programming :: Code Snippets :: Cpp :: Fast Variable Swapping

[ Fast Variable Swapping ]

Everyone knows the "traditional" method:

inline void swapInt(int& first, int& second)
   int temp = second;
   second = first;
   first = temp;

This method is not terribly fast but it works. If you want a little more speed you XOR (Exclusive OR) the two variables twice:

inline void fastSwap(int& first, int& second)
   first ^= second ^= first ^= second;

This method is a little bit faster but if you really want the highest performance possible you have to use ASM. The only disadvantage is that the code won't be platform-independent anymore:

#define ASM_SWAP(first,second) __asm   
   __asm mov eax, first /* Move first into eax */   
   __asm mov ecx, second /* second -> ecx */        
   __asm mov first, ecx  /* ecx -> first */        
   __asm mov second, eax  /* eax -> second */       

The macro ASM_SWAP swaps first and second using ASM. I tried to write an inline function it didn't work really... I am not an ASM-Master so I dont know why. Simply copy this function into your code and you'll have the fastest swap method possible. Happy Coding!

 Last edited 2003-01-27 23:17:34 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0