Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Constant Shootout
#!/usr/bin/env perl
use warnings;
use strict;
use Dumbbench;
use Readonly;
use Const::Fast;
use Data::Dumper;
$Data::Dumper::Deparse = 1;
use constant USE_CONSTANT_KEY => "key";
use constant USE_CONSTANT_VALUE => "value";
Readonly my $READONLY_KEY => "key";
Readonly my $READONLY_VALUE => "value";
const my $CONST_FAST_KEY => "key";
const my $CONST_FAST_VALUE => "value";
my $bench = Dumbbench->new(
target_rel_precision => 0.005, # seek ~0.5%
initial_runs => 1000, # the higher the more reliable
);
my %test_hash = ( key => "value" );
my %subs = (
use_constant => sub {
my $i = 0;
if (defined $test_hash{USE_CONSTANT_KEY()}) {
if ($test_hash{USE_CONSTANT_KEY()} eq USE_CONSTANT_VALUE) {
$i++;
}
}
},
readonly => sub {
my $i = 0;
if (defined $test_hash{$READONLY_KEY}) {
if ($test_hash{$READONLY_KEY} eq $READONLY_VALUE) {
$i++;
}
}
},
const_fast => sub {
my $i = 0;
if (defined $test_hash{$CONST_FAST_KEY}) {
if ($test_hash{$CONST_FAST_KEY} eq $CONST_FAST_VALUE) {
$i++;
}
}
},
);
warn Dumper(\%subs);
$bench->add_instances(
Dumbbench::Instance::PerlSub->new(name => 'use_constant', code => $subs{use_constant}),
Dumbbench::Instance::PerlSub->new(name => 'readonly', code => $subs{readonly}),
Dumbbench::Instance::PerlSub->new(name => 'const_fast', code => $subs{const_fast}),
);
$bench->run;
$bench->report;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment