Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: map vs for\foreach. (bench)

by tye (Sage)
on Mar 12, 2015 at 05:40 UTC ( [id://1119751]=note: print w/replies, xml ) Need Help??


in reply to Re: map vs for\foreach. (perf)
in thread map vs for\foreach.

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://1119751]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-24 22:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found