Let me start with a lesson I learned recently: with your code, you are not using the $a and $b you declared at the top. The code executes without warning because $a and $b are "reserved" variables in Perl (used in sorting). If you change the variables to something else (capitalize them), you get:
sub traditional { my $C = $A; $A = $B; $B = $C; } sub non_trad { ($B, $A) = ($A, $B); } Global symbol "$A" requires explicit package name at ./bench.perl line + 12. Global symbol "$B" requires explicit package name at ./bench.perl line + 13.
You should "use vars" to allow Benchmark to use the variables you want it to use.

This doesn't change the results, though, since you were (unknowingly) using "real" variables, anyway.

Here are some more possibilities, just to play around:

#!/usr/bin/perl -w use vars qw/$A $B @Arr/; use strict; use Benchmark; $A = rand(10); $B = rand(10); @Arr = ($A, $B); sub traditional { my $C = $A; $A = $B; $B = $C; } sub non_trad { ($B, $A) = ($A, $B); } sub array_slice1 { @Arr = @Arr[1,0]; } sub array_slice2 { @Arr[1,0] = @Arr; } timethese (100000, { "traditional" => \&traditional, "not traditional" => \&non_trad, "array1" => \&array_slice1, "array2" => \&array_slice2, }); Results: Benchmark: timing 100000 iterations of array1, array2, not traditional +, traditional... array1: 4 wallclock secs ( 3.98 usr + 0.00 sys = 3.98 CPU) array2: 3 wallclock secs ( 3.27 usr + 0.00 sys = 3.27 CPU) not traditional: 2 wallclock secs ( 2.72 usr + 0.00 sys = 2.72 CPU) traditional: 2 wallclock secs ( 1.81 usr + 0.00 sys = 1.81 CPU)

Russ
Brainbench 'Most Valuable Professional' for Perl


In reply to RE: simple swap... by Russ
in thread 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.