Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to swap values in C?

Tags:

performance

c

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.

like image 595
JawnV6 Avatar asked Aug 31 '08 15:08

JawnV6


People also ask

Is XOR swap fast?

On modern CPU architectures, the XOR technique can be slower than using a temporary variable to do swapping.

Is there any swap function in C?

To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.

What is swap in C programming?

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.


1 Answers

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

like image 141
caramelcarrot Avatar answered Oct 16 '22 06:10

caramelcarrot