Most of you are aware of the swap that doesn't use a temporary variable. I tested two swap() versions by passing references to two different arrays: 1) using bitwise XOR which avoids a temporary variable, and 2) a version that does use the temporary. My expectation was that the XOR would be faster. It actually is 4 times slower. I may have set the test up incorrectly. Either way, some of you assembly gurus know the reason for this result and, perhaps, would share it with me.
void swap(unsigned int& a, unsigned int& b)
{
b=(a+b)-(a=b); // This takes 8 seconds
a ^= b; // This takes about 12 seconds
b ^= a;
a ^= b;
/*
int temp; // This takes 4 seconds
temp = b;
b = a;
a = temp;
*/
}
void setup() {
unsigned int a[100];
unsigned int b[100];
int i, j;
unsigned long start, end;
Serial.begin(115200);
for (i = 0, j = 100; i < 100; i++, j--) {
a[i] = i;
b[i] = j;
}
for (i = 0; i < 100; i++) {
Serial.print("a[");
Serial.print(i);
Serial.print("] = ");
Serial.print(a[i]);
Serial.print(" b[] = ");
Serial.println(b[i]);
}
start = millis();
for (j = 0; j < 30001; j++) {
for (i = 0; i < 100; i++) {
swap(a[i], b[i]);
}
}
end = millis();
Serial.println( (end - start) / 1000);
Serial.println("=======================");
for (i = 0; i < 100; i++) {
Serial.print("a[");
Serial.print(i);
Serial.print("] = ");
Serial.print(a[i]);
Serial.print(" b[] = ");
Serial.println(b[i]);
}
}
void loop() {
}
Edit: I added a third method