I want to swap two integers, and I want to know which of these two implementations will be faster: The obvious way with a temp variable:
void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }
Or the xor version that I'm sure most people have seen:
void swap(int* a, int* b) { *a ^= *b; *b ^= *a; *a ^= *b; }
It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important.
On modern CPU architectures, the XOR technique can be slower than using a temporary variable to do swapping.
To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.
Swapping two number in C programming language means exchanging the values of two variables. Suppose you have two variable var1 & var2. Value of var1 is 20 & value of var2 is 40. So, after swapping the value of var1 will become 40 & value of var 2 will become 20.
Number 2 is often quoted as being the "clever" way of doing it. It is in fact most likely slower as it obscures the explicit aim of the programmer - swapping two variables. This means that a compiler can't optimize it to use the actual assembler ops to swap. It also assumes the ability to do a bitwise xor on the objects.
Stick to number 1, it's the most generic and most understandable swap and can be easily templated/genericized.
This wikipedia section explains the issues quite well: http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With