Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: map vs for\foreach. (perf)

by tye (Sage)
on Mar 11, 2015 at 15:49 UTC ( [id://1119661]=note: print w/replies, xml ) Need Help??


in reply to map vs for\foreach.

Picking your syntax based on benchmarks of trivial operations is total folly.

Use map if you want to get back a list. Don't otherwise.

Now, there can be non-trivial performance implications in similar syntax choices between for() and while() when reading from a (large) file, for example. But you also likely would not discover those from running benchmarks of trivial operations.

The benchmark results presented so far mostly illustrate differences in the trivial operations being done, not any performance difference that is likely to actually matter if you were changing useful code between map/for() [for cases of code where for() made sense].

- tye        

Replies are listed 'Best First'.
Re^2: map vs for\foreach. (bench)
by tye (Sage) on Mar 12, 2015 at 05:40 UTC

    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        

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-25 14:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found