What is the fastest way to swap values in C?

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

Leave a Comment