in reply to performance of map vs. foreach
#!/usr/bin/perl use strict; use warnings; use Benchmark qw /cmpthese/; cmpthese(-1, { m_exp1 => sub {my %hash; map $hash{$_} = 1, 1 .. 10_000}, m_blk1 => sub {my %hash; map {$hash{$_} = 1} 1 .. 10_000}, f_exp1 => sub {my %hash; $hash{$_} = 1 foreach 1 .. 10_000}, f_blk1 => sub {my %hash; foreach (1 .. 10_000) {$hash{$_} = 1}}, m_exp2 => 'my %hash; map $hash{$_} = 1, 1 .. 10_000', m_blk2 => 'my %hash; map {$hash{$_} = 1} 1 .. 10_000', f_exp2 => 'my %hash; $hash{$_} = 1 foreach 1 .. 10_000', f_blk2 => 'my %hash; foreach (1 .. 10_000) {$hash{$_} = 1}', }); __END__ Rate m_blk2 m_exp2 f_blk1 m_exp1 f_blk2 f_exp2 f_exp1 m_blk1 m_blk2 38.0/s -- -5% -7% -9% -10% -10% -13% -14% m_exp2 39.8/s 5% -- -2% -5% -5% -6% -9% -10% f_blk1 40.7/s 7% 2% -- -3% -3% -4% -7% -8% m_exp1 41.9/s 10% 5% 3% -- -0% -1% -4% -5% f_blk2 42.1/s 11% 6% 3% 0% -- -1% -4% -5% f_exp2 42.3/s 11% 6% 4% 1% 1% -- -3% -4% f_exp1 43.8/s 15% 10% 8% 5% 4% 4% -- -1% m_blk1 44.2/s 17% 11% 9% 6% 5% 5% 1% --
There's no significant difference. Note that the map-block form is both the fastest and the slowest (fastest in the sub form, slowest in the string form, although there's an overhead when calling subs).
This was done with perl 5.8.6. With older perls, you might find map to be slower.
|
|---|