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
|
|---|