Define quicker. foreach() is quicker but mapping to a hash allows for multiple lookups and is less typing.
#!/usr/bin/perl
use Benchmark 'cmpthese';
use warnings;
@array = ( 'a'..'z' );
$value = 'z';
my $res;
my $position;
print "for(): ".traditional()."\tforeach: ".for_each()."\tmap: ".mapto
+hash()."\n";
cmpthese ( 10000, { for_loop => '$res = traditional()',
map => '$res = maptohash()',
for_each => '$res = for_each()',
}
);
sub traditional{
for ($position=0; $position <= $#array; $position++) {
last if ($array[$position] eq $value);
}
return $position;
}
sub for_each{
for our $position ( 0..$#array ) {
last if ($array[$position] eq $value) ;
}
return $position;
}
sub maptohash{
%indexed = map{ $array[$_], $_ } (0..$#array);
return $indexed{$value};
}
%perl foo.pl [7:41pm]
for(): 25 foreach: 25 map: 25
Rate map for_loop for_each
map 5100/s -- -40% -72%
for_loop 8477/s 66% -- -53%
for_each 18028/s 254% 113% --
s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s
|-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,,
$|=1,select$,,$,,$,,1e-1;print;redo}