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:

    “Adolescents, for all their self-involvement, are emerging from the self-centeredness of childhood. Their perception of other people has more depth. They are better equipped at appreciating others’ reasons for action, or the basis of others’ emotions. But this maturity functions in a piecemeal fashion. They show more understanding of their friends, but not of their teachers.”
    —Terri Apter (20th century)

    “One of the great reasons for the popularity of strikes is that they give the suppressed self a sense of power. For once the human tool knows itself a man, able to stand up and speak a word or strike a blow.”
    —Charles Horton Cooley (1864–1929)

    “Tax avoidance means that you hire a $250,000-fee lawyer, and he changes the word ‘evasion’ into the word ‘avoidance.’”
    —Franklin D. Roosevelt (1882–1945)

    “The mayor and Montaigne have always been two, with a very clear separation. For all of being a lawyer or a financier, we must not ignore the knavery there is in such callings. An honest man is not accountable for the vice or stupidity of his trade, and should not therefore refuse to practice it.”
    —Michel de Montaigne (1533–1592)