Perl sub Benchmark

This is a Benchmark about the subroutines in Perl:

use Benchmark qw(:all) ;
 
sub calc { return($_[0]*$_[1]);}

my %subs;
$subs{'calc1'} = eval 'sub { return($_[0]*$_[1]);}';
$subs{'calc2'} = sub { return($_[0]*$_[1]);};
print $subs{'calc1'}->(1234,1234).$/;
print $subs{'calc2'}->(1234,1234).$/;
print calc(1234,1234).$/;
 
cmpthese(-2, {
'normal'  => sub {calc(1234,1234)},
'comp'    => sub {$subs{'calc1'}->(1234,1234);},
'ref'     => sub {$subs{'calc2'}->(1234,1234);},
});

Result:

1522756
1522756
1522756
            Rate    ref   comp normal
ref    1920352/s     --    -4%   -17%
comp   1996495/s     4%     --   -14% 
normal 2313035/s    20%    16%     --

We see the normal way is the best solution.

One thought on “Perl sub Benchmark”

Leave a Reply

Your email address will not be published.

nineteen − seventeen =