Your benchmark isn't comparing for-block vs map. It's comparing the for
statement modifier against map. Statements modifiers don't have the overhead of entering and leaving a scope. Of course, in this particular case, the clear winner is one that doesn't loop.
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw /cmpthese/;
my $base = 1000;
foreach my $mult (1, 10, 100) {
my $code;
my $max = $mult * $base;
{
no strict 'refs';
@{"main::array$mult"} = 1 .. $max;
}
my $map_var = "\$sum${mult}map";
my $for_var = "\$sum${mult}for";
my $mod_var = "\$sum${mult}mod";
my $exp_var = "\$sum${mult}exp";
$code -> {"map${mult}k"} = "$map_var = 0;" .
"map {$map_var += \$_} \@array$mult";
$code -> {"for${mult}k"} = "$for_var = 0;" .
"for (\@array$mult) {$for_var += \$_}";
$code -> {"mod${mult}k"} = "$mod_var = 0;" .
"$mod_var += \$_ for \@array$mult";
$code -> {"exp${mult}k"} = "$exp_var = $max * ($max + 1) / 2;";
cmpthese -1 => $code;
print "\n";
no strict 'refs';
die "Unequal\n" unless ${"sum${mult}map"} == ${"sum${mult}for"} &&
${"sum${mult}mod"} == ${"sum${mult}exp"} &&
${"sum${mult}map"} == ${"sum${mult}exp"};
}
__END__
Rate map1k for1k mod1k exp1k
map1k 1305/s -- -58% -64% -100%
for1k 3140/s 141% -- -12% -100%
mod1k 3589/s 175% 14% -- -100%
exp1k 6859842/s 525617% 218353% 191047% --
Rate map10k for10k mod10k exp10k
map10k 123/s -- -59% -66% -100%
for10k 299/s 144% -- -16% -100%
mod10k 356/s 190% 19% -- -100%
exp10k 7021713/s 5717581% 2347785% 1970572% --
Rate map100k for100k mod100k exp100k
map100k 12.3/s -- -60% -64% -100%
for100k 30.5/s 148% -- -11% -100%
mod100k 34.2/s 179% 12% -- -100%
exp100k 5383313/s 43894609% 17663897% 15724842% --
Abigail