There has been some recent discussions about the virtues of map vs. foreach ("advanced" Perl functions and maintainability). The perldoc for map indicates that they are pretty much the same. I did the following comparison in terms of their performance:
use strict; use Benchmark qw(:all); timethese(1000,{ "Foreach" => sub{ my %hash = map{$_=>1} (1..10000);}, "Map" => sub{ my %hash; $hash{$_} = 1 foreach (1..10000);} })
I got the following:
Benchmark: timing 1000 iterations of Foreach, Map... Foreach: 54 wallclock secs (49.54 usr + 0.12 sys = 49.66CPU) @ 20. +14/s (n=1000) Map: 31 wallclock secs (28.80 usr + 0.06 sys = 28.86CPU) @ 34. +65/s (n=1000)
So it seems map is faster, or I'm doing something incorrect?

Note: Oops, as pointed out by ikegami, my Map and Foreach are reversed. I'll leave it as is, so not to confuse the comments. Thanks.


In reply to 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.