Unfortunately, you can't access the lexical hash variable from a string-evaled code in Benchmark, so the benchmarks measures nothing.
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use Benchmark qw{ cmpthese };
my %hl;
@hl{1001 .. 2000} = (1) x 1000;
our %hg = %hl;
our ($el, $vl, $eg, $vg) = (0) x 4;
die unless $hl{1001};
die unless $hg{1001};
cmpthese(-1, {
exist_l => q{ ++$el if exists $hl{1001} },
value_l => q{ ++$vl if $hl{1001} },
exist_g => q{ ++$eg if exists $hg{1001} },
value_g => q{ ++$vg if $hg{1001} },
});
say join "\n", "el: $el", "vl: $vl", "eg: $eg", "vg: $vg";
5.26.1 on Linux:
Rate value_g exist_g value_l exist_l
value_g 17625636/s -- -4% -47% -53%
exist_g 18303545/s 4% -- -45% -51%
value_l 33363781/s 89% 82% -- -11%
exist_l 37417325/s 112% 104% 12% --
el: 0
vl: 0
eg: 23229990
vg: 23229990
Blead gives smaller differences, but the order is the same.
Update: Changing q{ to sub { changes the order randomly and makes the difference less than 10%.
Update 2: Changing 1001 to 2001 in the benchmarked code (i.e. testing non-existent key) changes the differences to 20% and less, e.g.
Rate value_g exist_g value_l exist_l
value_g 31977080/s -- -2% -8% -19%
exist_g 32733979/s 2% -- -6% -17%
value_l 34737228/s 9% 6% -- -12%
exist_l 39658833/s 24% 21% 14% --
map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.