XOR Swap Algorithm - Reasons For Avoidance in Practice

Reasons For Avoidance in Practice

Most modern compilers can optimize away the temporary variable in the naive swap, in which case the naive swap uses the same amount of memory and the same number of registers as the XOR swap and is at least as fast, and often faster. The XOR swap is also much less readable and completely opaque to anyone unfamiliar with the technique.

On modern CPU architectures, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute instructions in parallel via instruction pipelines. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order. If efficiency is of tremendous concern, it is advised to test the speeds of both the XOR technique and temporary variable swapping on the target architecture.

Read more about this topic:  XOR Swap Algorithm

Famous quotes containing the words reasons for, reasons, avoidance and/or practice:

    Youth does not require reasons for living, it only needs pretexts.
    José Ortega Y Gasset (1883–1955)

    Science is the knowledge of many, orderly and methodically
    digested and arranged, so as to become attainable by one. The
    knowledge of reasons and their conclusions constitutes abstract, that of causes and their effects, and of the laws of nature, natural science.
    John Frederick William Herschel (1792–1871)

    Real good breeding, as the people have it here, is one of the finest things now going in the world. The careful avoidance of all discussion, the swift hopping from topic to topic, does not agree with me; but the graceful style they do it with is beyond that of minuets!
    Thomas Carlyle (1795–1881)

    As an example of just how useless these philosophers are for any practice in life there is Socrates himself, the one and only wise man, according to the Delphic Oracle. Whenever he tried to do anything in public he had to break off amid general laughter. While he was philosophizing about clouds and ideas, measuring a flea’s foot and marveling at a midge’s humming, he learned nothing about the affairs of ordinary life.
    Desiderius Erasmus (c. 1466–1536)