Benchmarks:

#!/usr/bin/perl use strict; use warnings; use Benchmark qw( cmpthese ); my @c = 1 .. 1_000_000; cmpthese( -3, { for => sub { my @e; for my $c ( @c ) { my $d = $c % 2; push @e, $d if !$d; } }, for2 => sub { my @e; for my $c ( @c ) { push @e, 0 if !( $c % 2 ); } }, map_grep => sub { my @e = grep !$_, map $_ % 2, @c; }, map => sub { my @e = map $_ % 2 ? () : 0, @c; }, grep_x => sub { my @e = ( 0 ) x grep !( $_ % 2 ), @c; }, grep_for => sub { my @e; push @e, 0 for 1 .. grep !( $_ % 2 ), @c; }, } );
Rate map_grep for grep_for map for2 grep_x map_grep 10.6/s -- -27% -43% -47% -51% -54% for 14.6/s 38% -- -21% -27% -33% -36% grep_for 18.4/s 75% 27% -- -7% -15% -20% map 19.9/s 88% 36% 8% -- -9% -13% for2 21.7/s 106% 49% 18% 9% -- -5% grep_x 22.9/s 117% 57% 24% 15% 6% -- Rate map_grep for grep_for map for2 grep_x map_grep 12.2/s -- -16% -34% -40% -45% -49% for 14.6/s 20% -- -22% -29% -35% -39% grep_for 18.6/s 52% 27% -- -9% -17% -23% map 20.5/s 68% 40% 10% -- -8% -15% for2 22.4/s 83% 53% 20% 9% -- -7% grep_x 24.1/s 97% 65% 29% 17% 8% -- Rate map_grep for grep_for map for2 grep_x map_grep 12.1/s -- -19% -31% -36% -45% -49% for 14.8/s 23% -- -15% -21% -32% -37% grep_for 17.4/s 44% 17% -- -8% -21% -27% map 18.8/s 56% 27% 8% -- -14% -21% for2 21.9/s 82% 48% 26% 16% -- -8% grep_x 23.7/s 97% 60% 37% 26% 8% --

In reply to Re^2: Speed comparison of foreach vs grep + map by ikegami
in thread Speed comparison of foreach vs grep + map by mldvx4

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.