As brian d foy pointed out, you're not doing the same thing. Furthermore, you're using a blocked map, vs a foreach statement modifier. If you want to be fair, you should to the same thing. Below is a benchmark that does the same thing in all cases. It also compares the block form and the expression form. And to top it off, all the cases appear as a coderef, and as a string.
#!/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.


In reply to Re: performance of map vs. foreach by Anonymous Monk
in thread performance of map vs. foreach by johnnywang

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.