Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: map vs for\foreach.

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


in reply to Re^2: map vs for\foreach.
in thread map vs for\foreach.

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; }, } );

Results:

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2019-06-24 09:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Is there a future for codeless software?



    Results (97 votes). Check out past polls.

    Notices?