Actually since 5.8.1 map in void context is optimized to not construct a return list. (Update: although I'm still get map 7-14% slower no matter how I twiddle your benchmark; scratch that, see below)

Having said that, it's still poor form to use map as a replacement for a proper for loop though (IMHO). Using for says you're iterating over a list of values, whereas using map emphasizes the fact that the point of the iteration is constructing a new list from the existing list (or put another way: for means "I'm walking this list for some reason", whereas map screams "HEY, I WANT TO HAVE A NEW LIST HERE").

Update: Aha, I think I know what the problem is. Try appending a 1; in your sub after the map so that you're explicitly putting the map in void context (since it'll no longer be the last expression in the sub and hence the return value). That makes map a hair (7%) faster for me (5.8.8 on OS X).

Oop: I also changed to use map EXPR, LIST rather than map BLOCK LIST so that's saving me overhead vs for as well.

use strict; use Benchmark qw(cmpthese); my @a1 = (1)x4_000; cmpthese(4_000, { for_loops => sub { for(@a1) { $_ = $_ + 1 } }, map_loops => sub { map $_ = $_ + 1, @a1; 1 }, }); __END__             Rate for_loops map_loops for_loops 1724/s        --       -6% map_loops 1826/s        6%        --

So you can make it a tiny bit faster (due to being able to "cheat" a little and avoid the enter/leave block overhead), but again I'd stick to using map just for map'ing not general iteration.

The cake is a lie.
The cake is a lie.
The cake is a lie.


In reply to Re^4: Scanning a list for indices by Fletch
in thread Scanning a list for indices by cmv

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.