Benchmark Debug Perl

today we want to take a look whats the fastest way to debug our code in Perl:

#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(:all) ;

use constant {
DEBUG1 => 1,
DEBUG2 => 0
};

my $DEBUG1 = 1;
my $DEBUG2 = 0;
 
cmpthese(-10, {
'if_constant' 	=> sub {if(DEBUG1){print "";}print ""; },
'if_var' 	=> sub {if($DEBUG1){print "";}print ""; },
'and_constant' 	=> sub {DEBUG1 and print "";print "";},
'and_var' 	=> sub {$DEBUG1 and print "";print "";},
});

print $/;

cmpthese(-10, {
'if_constant' 	=> sub {if(DEBUG2){print "";}print ""; },
'if_var' 	=> sub {if($DEBUG2){print "";}print ""; },
'and_constant' 	=> sub {DEBUG2 and print "";print "";},
'and_var' 	=> sub {$DEBUG2 and print "";print "";},
});

and the Benchmark result is this:

                  Rate      and_var  if_constant       if_var and_constant
and_var      6347385/s           --          -7%          -9%         -25%
if_constant  6814160/s           7%           --          -3%         -19%
if_var       7008445/s          10%           3%           --         -17%
and_constant 8427633/s          33%          24%          20%           --

                   Rate      and_var       if_var  if_constant and_constant
and_var       8482773/s           --         -17%         -28%         -37%
if_var       10257262/s          21%           --         -13%         -24%
if_constant  11838939/s          40%          15%           --         -12%
and_constant 13490170/s          59%          32%          14%           --

We see that the best solution in both ways is to use a constant with “and”.It seems to me the compiler remove the constant and the print, becaus if you dont have the print after the command it ends in a infinite loop.

Leave a Reply

Your email address will not be published.

19 − ten =