A modern optimizing compiler will probably do a better job making these kinds of optimization decisions than you can. They're quite good! Let's look at how different compiler optimization flags can affect the outcome of this program:
Code:
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
DWORD oldtick;
unsigned int count, x, y, temp;
//
// XOR swap
//
count = 0xFFFFFFFF;
x = 0x00000000;
y = 0xFFFFFFFF;
oldtick = GetTickCount();
while (count--)
{
x ^= y;
y ^= x;
x ^= y;
}
cout << "XOR swap time: " << (GetTickCount() - oldtick) << " ms" << endl;
//
// Tmp swap
//
count = 0xFFFFFFFF;
x = 0x00000000;
y = 0xFFFFFFFF;
oldtick = GetTickCount();
while (count--)
{
temp = x;
x = y;
y = temp;
}
cout << "Temp swap time: " << (GetTickCount() - oldtick) << " ms" << endl;
return 0;
}
(With MSVC)
Optimizations disabled
Code:
XOR swap time: 21497 ms
Temp swap time: 11154 ms
Optimize for speed
Code:
XOR swap time: 3807 ms
Temp swap time: 2527 ms
Full optimization
Code:
XOR swap time: 9906 ms
Temp swap time: 9267 ms
Optimize for size
Code:
XOR swap time: 3791 ms
Temp swap time: 2543 ms
Another XOR trick is to use it to zero-out memory, but guess what? Optimizing compilers use that too!