eduardo has asked for the wisdom of the Perl Monks concerning the following question:
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:#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
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:($b, $a) = ($a, $b); #swap two variables
which basically says, in a nutshell... the traditional 3 value approach is faster... anyone care to explain to me why?#!/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)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: simple swap...
by Russ (Deacon) on Jul 22, 2000 at 00:21 UTC | |
by japhy (Canon) on Jul 22, 2000 at 01:19 UTC | |
by Russ (Deacon) on Jul 22, 2000 at 01:28 UTC | |
by japhy (Canon) on Jul 22, 2000 at 01:35 UTC | |
|
Re: simple swap...
by japhy (Canon) on Jul 21, 2000 at 23:07 UTC | |
by raflach (Pilgrim) on Jul 21, 2000 at 23:18 UTC | |
|
(Ovid) Re: simple swap...
by Ovid (Cardinal) on Jul 21, 2000 at 23:21 UTC | |
|
Re: simple swap...
by athomason (Curate) on Jul 22, 2000 at 00:19 UTC | |
|
RE: simple swap...
by jlistf (Monk) on Jul 21, 2000 at 23:34 UTC | |
|
RE: simple swap...
by steveAZ98 (Monk) on Jul 22, 2000 at 23:46 UTC |