Perl Print Benchmark

This is a little Benchmark about the print function in Perl with var and constant.

use strict;
use warnings;
use Benchmark qw(:all) ;
use constant {
CVAR1 => 'aaa',
CVAR2 => 'bbb'
my $VAR1 = 'aaa';
my $VAR2 = 'bbb';

cmpthese(-4, {
'constant' 	=> sub {print CVAR1.' '.CVAR2; },
'interpolate' 	=> sub {print "$VAR1 $VAR2"; },
'concate' 	=> sub {print ''.$VAR1.' '.$VAR2; },

cmpthese(-4, {
'var' 	=> sub {print "$/"; },
'char' 	=> sub {print "n"; },

Our first result let us see that you should use constants if possible, this makes your program faster and clear.In the other case you should interpolate the variable into the string.

    Rate     concate interpolate    constant
concate     1219741/s          --         -6%        -28%
interpolate 1295612/s          6%          --        -24%
constant    1700436/s         39%         31%          --

Its faster to use the direct n but i think in some cases its better to use the default $/ variable.

         Rate  var char
var  281773/s   --  -6%
char 298788/s   6%   --

I made the last to show you the differences you could use the way you like.

Leave a Reply

Your email address will not be published.

seventeen − 5 =