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)
In reply to simple swap... by eduardo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |