perl map vs for Benchmark

I want to test what’s the different between a map function and a for iteration with Perl is:

#!/usr/bin/perl
use strict;
use Benchmark qw(:all) ;
my @arr = (1..10);


print sub_map(@arr).$/;
print sub_for(@arr).$/;



cmpthese(-1, {
'sub_map'  => sub {sub_map(@arr)},
'sub_for'  => sub {sub_for(@arr)},
});

sub sub_map {
    return join",", map {$_ * 2} @_;
}
sub sub_for {
    for (@_){
        $_ = $_*2;
    }
    return(join",",@_);
}

Our Benchmark result:

2,4,6,8,10,12,14,16,18,20        
2,4,6,8,10,12,14,16,18,20        
            Rate sub_for sub_map 
sub_for 129153/s      --    -10% 
sub_map 142717/s     11%      --

map is about 11% faster than a simple for loop.

2 thoughts on “perl map vs for Benchmark”

  1. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my
    blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and
    was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy
    reading your blog and I look forward to your new updates.

Leave a Reply

Your email address will not be published.

5 × two =