I've learned that Xor operation can be used to implement effective swap function. like this:
template<class T>
void swap(T& a, T& b)
{
a = a^b;
b = a^b;
a = a^b;
}
But the implementation of swap all i can found on the internet is essentially like this:
template<class T>
void swap(T& a, T& b)
{
T temp(a);
a = b;
b = temp;
}
It seems that the compiler didn't generate the same code for the two form above because I tested it on VC++ 2010 and the first one is done the job more quickly than std::swap
. Is there portable or any other problem with first one? Feel free to correct any of my mistake cause i'm not an English native and not good at C++.
(Editor's note: likely that test was done with a non-optimized debug build, not a release build where std::swap
could inline. Benchmarking debug builds is meaningless. Compilers generally don't optimize away xor-swap into something more efficient.)
XCHG reg, reg
could be used possibly, though I doubt it is ever needed - renaming the registers is even faster. I have written a few k lines of assembly, I have never felt the urge to usexchg
for swapping values. – Pixmov
s on my machine. – Carousal