Here's some trivial benchmarks that at least compare comparable operations and ones that are just slightly more than trivial:

#!/usr/bin/perl -w use strict; use Benchmark 'cmpthese'; my @a = 1..1000; sub p { my( $a ) = @_; if( $a & 1 ) { return $a*$a; } else { return ($a-1)*($a+1); } } cmpthese( -2, { for => sub { my $t = 0; for( @a ) { $t += p($_) } return $t }, map => sub { my $t = 0; map $t += p($_), @a; return $t }, } ); cmpthese( -2, { map => sub { my @b = map p($_), @a; return $b[-1] }, for => sub { my @b; for( @a ) { push @b, p($_) } return $b[-1] }, } );

And here are my results:

Rate for map for 2101/s -- -1% map 2127/s 1% -- Rate map for map 1981/s -- -0% for 1987/s 0% --

So I don't even have to give my explanation of why Benchmark.pm saying "20% faster" almost never has any practical meaning.

- tye        


In reply to Re^2: map vs for\foreach. (bench) by tye
in thread map vs for\foreach. by builat

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.