Your Foreach test uses map, and your Map test uses foreach. You're making me dizzy. After fixing the test names and running the test for 10 seconds, foreach was 76% faster than map:

Rate Map Foreach Map 21.9/s -- -43% Foreach 38.6/s 76% --

Foreach is faster as expected, since foreach doesn't have to build a long list like map does. Update: I wrote a foreach loop that builds an array which is later assigned to %hash. As you can see below, "Map" and "Map-like" have very similar results, as expected.

use strict; use Benchmark (); Benchmark::cmpthese(-10, { "Map" => sub { my %hash = map{$_=>1} (1..10000); }, "Foreach" => sub { my %hash; $hash{$_} = 1 foreach (1..10000); }, "Map-like" => sub { my @a; push(@a, $_, 1) foreach (1..10000); my %hash = @a; }, }) __END__ Rate Map-like Map Foreach Map-like 21.5/s -- -1% -44% Map 21.8/s 1% -- -43% Foreach 38.6/s 80% 77% --

In reply to Re: performance of map vs. foreach by ikegami
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.