A new benchmark trying to measure only the effect of the data structure being used. No need for further comments except that it is an entirely different benchmark:
use strict;
use warnings;
use Benchmark qw/cmpthese/;
my @translation = qw / Zero One Two Three Four Five Six/;
my %trans = (1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "
+Five", 6 => "Six");
my @dispatch = ( sub {return "Zero"}, sub {return "One"}, sub {return
+"Two"}, sub {return "Three"}, sub {return "Four"}, sub {return "Five"
+}, sub {return "Six"} );
sub test2 {
my $var2 = shift;
return ("One") if ($var2 == 1 );
return ("Two") if ($var2 == 2 );
return ("Three") if ($var2 == 3 );
return ("Four ") if ($var2 == 4 );
return ("Five") if ($var2 == 5 );
return undef;
}
sub test3 {
my $var2 = shift;
return $translation[$var2];
}
sub test4 {
my $var = shift;
return $trans{$var} ;
}
sub test5 {
my $var = shift;
eval { goto "_$var" } or
return "Other";
_1: return "One" ;
_2: return "Two" ;
_3: return "Three";
_4: return "Four";
_5: return "Five";
}
sub test6 {
my $var = shift;
return $dispatch[($var)]->();
}
cmpthese( -1,
{
_linear_2 => q {test2("5")},
_array => q {test3("5")},
_hash => q {test4("5")},
_goto => q {test5("5")},
_dispatch => q {test6("5")},
}
)
And the results:
$ perl test_if.pl
Rate _goto _linear_2 _dispatch _hash _array
_goto 1247485/s -- -17% -26% -50% -52%
_linear_2 1509714/s 21% -- -11% -40% -42%
_dispatch 1688450/s 35% 12% -- -33% -36%
_hash 2513434/s 101% 66% 49% -- -4%
_array 2621427/s 110% 74% 55% 4% --
Have a nice evening.