Ok, so as an update in benchmarking, I have written a quick benchmark of the 3 main swapping mechanisms I see written here. I also wanted to say, that the xor technique really just blew me away... never seen that before... anyways, here are some benchmarks:
#!/usr/bin/perl -w
use vars qw/$a $b/;
use strict;
use Benchmark;
$a = 0;
$b = 1;
sub traditional {
my $c = $a;
$a = $b;
$b = $c;
}
sub arrays {
($b, $a) = ($a, $b);
}
sub xor {
$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;
}
timethese(-5, {
trad => \&traditional,
arrays => \&arrays,
xor => \&xor,
});
[ed@ci478467-a ed]$ perl swap.pl
Benchmark: running arrays, trad, xor, each for at least 5 CPU seconds.
+..
arrays: 5 wallclock secs ( 5.12 usr + 0.00 sys = 5.12 CPU) @ 24
+242.19/s (n=124120)
trad: 6 wallclock secs ( 5.00 usr + 0.01 sys = 5.01 CPU) @ 40
+630.74/s (n=203560)
xor: 5 wallclock secs ( 5.11 usr + 0.00 sys = 5.11 CPU) @ 30
+829.16/s (n=157537)
so unfortunatelly, as amazingly cool as the XOR swap is, it seem slike it is slighly slower in perl than just using 3 variables... curses :)