Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: map vs for\foreach.

by sn1987a (Chaplain)
on Mar 11, 2015 at 14:33 UTC ( #1119641=note: print w/replies, xml ) Need Help??

in reply to map vs for\foreach.

You are not comparing apples to apples. You map loop assigns (copies) the entire array in addition to incrementing each element. If you drop the assignment, map beats foreach.

My results

foreach(@a){$_+=1;}; real 0m4.941s user 0m1.096s sys 0m3.604s
@a = map{$_+= 1} @a; real 0m6.248s user 0m2.652s sys 0m2.900s
map{$_+= 1} @a; real 0m3.224s user 0m2.908s sys 0m0.232s

Note: It is generally considered poor form to use map only for its side effects.

Updated to clean up and add note

Update 2:

More rigorous timing show that foreach is indeed faster --> Re^3: map vs for\foreach.

Replies are listed 'Best First'.
Re^2: map vs for\foreach.
by builat (Monk) on Mar 11, 2015 at 14:38 UTC
    In my case:
    foreach(@a){$_+=1;}; real 0m3.756s user 0m3.588s sys 0m0.120s

    map{$_+= 1} @a; real 0m5.233s user 0m5.056s sys 0m0.164s

      My previous timings where just from a single run of each program. Using Benchmark and repeating to verify consistent results, I find that foreach is indeed faster.

      use strict; use warnings; use Benchmark; my @a; $a[$_] = int( rand(100) ) for ( 0 .. 10000000 ); cmpthese( -30, { 'foreach' => sub { foreach (@a) { $_ += 1; } }, 'map (assign)' => sub { @a = map { $_ += 1 } @a; }, 'map (bare)' => sub { map { $_ += 1 } @a; }, } );


      s/iter map (assign) map (bare) foreach map (assign) 2.06 -- -40% -76% map (bare) 1.23 67% -- -59% foreach 0.501 311% 146% --

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1119641]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2019-04-26 11:38 GMT
Find Nodes?
    Voting Booth?
    I am most likely to install a new module from CPAN if:

    Results (128 votes). Check out past polls.

    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!