A warning to amateurs:
All of the techniques under this heading (with the
(possible) exception of the
Perl method)
rely on A and B not occupying the same location
in
RAM). They will yield zero for both values
if the two variables have the same
address.
While this may at first seem irrelevant, one often uses
such a swap on
array elements, for example after
finding the minimum value during a pass of a
sorting
algorithm. In such a situation, the
programmer must
check that the two items to swap do not have the same
array index.
If such a possibilty exists, using a third (
scratch)
variable to perform a swap (rather than an index
check at every pass) will often yield significantly
faster
code than performing the swap in-place.
Additionally, implicit use of register variables
by the compiler, and
branch prediction penalties
in a given CPU architecture will magnify this
difference greatly.