in reply to simple swap...

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

Replies are listed 'Best First'.
RE: RE: simple swap...
by japhy (Canon) on Jul 22, 2000 at 01:19 UTC
    Your array slicing is unfair, since you create the array beforehand.

    $_="goto+F.print+chop;\n=yhpaj";F1:eval
      I'm not sure I understand what you mean. The variables being swapped are created beforehand in both methods. In the first examples, they are separate variables. In my second example, they are members of an array. Each of the subs swap the values in two variables.

      I mainly included them to point out:

      • TMTOWTDI
      • My benchmarks show arrays are even slower than the lists in the first example.
      :-)

      Russ
      Brainbench 'Most Valuable Professional' for Perl

        I was saying that if you were using them as examples of putting the variables in the array and swapping them, well, for one, that doesn't switch the variables, just the elements of the array; and two, your test should've included the process of forming the array. But nevermind.

        $_="goto+F.print+chop;\n=yhpaj";F1:eval