http://www.perlmonks.org?node_id=997340


in reply to Re^2: Efficiency of map vs. more verbose basic/fundamental code
in thread Efficiency of map vs. more verbose basic/fundamental code

I tried your benchmark and I also see map is faster. When I changed subs to return concatenated results, for loop becomes faster. I wonder why?

#!/usr/bin/perl use strict; use warnings; use Benchmark qw/cmpthese/; my %h = map {$_ => $_} 1 .. 10000; sub test1{ my $buff=''; foreach my $key (sort keys %h) { $buff.="$key: $h{$key}\n"; } return $buff; } sub test2{ return join('', map "$_: $h{$_}\n", sort keys %h); } print test1() eq test2() ? "same\n" : "not same\n"; my %tests = ( '01_for' => \&test1, '02_map' => \&test2, ); cmpthese( -10, #for 10 cpu secs \%tests ); __DATA__ Rate 02_map 01_for 02_map 33.9/s -- -16% 01_for 40.2/s 19% --
update:
I remember previous thread. "for loop" consumes lots of memory compared to while loop.