Perl Constant Benchmark

Today we want to take a look about constant and the speed vs vars.

use strict;
use warnings;
use Benchmark qw(:all) ;
use constant {
PI => 3.14
my $PI = 3.14;
my $cache  = 0;

cmpthese(-4, {
'constant' 	=> sub {$cache =  PI * 10; },
'var' 		=> sub {$cache = $PI * 10; },


The Benchmark result look like this:

               Rate      var constant
var      24064778/s       --     -10%
constant 26633876/s      11%       --

We see Perl optimizes our code and so we should use constants if we could, for more constant tricks see Benchmark Debug Perl.

It is also possible fore use modules, take a look at Perl use module only for debugging.

2 thoughts on “Perl Constant Benchmark”

  1. Generally I do not read article on blogs, but I wish to say that this write-up very forced me to take a look at and do so!
    Your writing style has been surprised me. Thanks, quite great article.

  2. Your style is really unique in comparison to other people I’ve read stuff from.
    Thank you for posting when you have the opportunity, Guess I will just book mark this site.

Leave a Reply

Your email address will not be published.

20 − eleven =