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 :)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.