one of the most basic operations you can do in a program is the swapping of two variables. who here can't remember sitting in their first programming class and being taught that the proper algorithm for swapping two variables was:
#define 3 variables, 2 for storage, one for temp... my ($a, $b, $c); #set the two variables to some value $a = 5; $b = 6; #use the temp value to swap them $c = $a; $a = $b; $b = $c; #now, $a has $b and $b has what $a had
and then, you left feeling pretty good about yourself, until you encountered perl (and languages like it...) that alowed you to do this wonderful thing:
($b, $a) = ($a, $b); #swap two variables
well, i was thinking about this, and questioned, i wonder what the great oracle of benchmark would say about this... and the results were quite suprising:
#!/usr/bin/perl -w use strict; use Benchmark; my $a = rand(10); my $b = rand(10); sub traditional { my $c = $a; $a = $b; $b = $c; } sub non_trad { ($b, $a) = ($a, $b); } timethese (-10, { "traditional" => \&traditional, "not traditional" => \&non_trad, }); [ed@darkness ed]$ perl swap.pl Benchmark: running not traditional, traditional, each for at least 10 CPU seconds... not traditional: 11 wallclock secs (10.25 usr + 0.00 sys = 10.25 CPU) + @ 302846.15/s (n=3104173) traditional: 11 wallclock secs (10.83 usr + 0.00 sys = 10.83 CPU) @ 4 +91714.04/s (n=5325263)
which basically says, in a nutshell... the traditional 3 value approach is faster... anyone care to explain to me why?

In reply to simple swap... by eduardo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.