When you see operations per second that high, you should ask yourself if any work is being done. In fact, none really is, and your benchmark is rendered totally unreliable as a result. First, you have scoping issues. And even if you fix those, you remain with the issue that choroba identified; that the first benchmark iteration deletes from the master copy of the hash, leaving remaining iterations with less work to do.
Here's a version that codes around the scoping issues that evaled code creates, and that makes a copy of %hosts on each iteration. That copy costs time, but it costs the same amount of time for each snippet.
use Benchmark qw(cmpthese);
our $t_count = 3;
our %hosts = map { $_ => $t_count - ( rand 50 > 49 ? 1 : 0 ) } (1 ..
+1000);
my $count = 10000;
cmpthese($count, {
do => 'my %t = %main::hosts; do { delete $t{$_} unless $t{$_} ==
+$main::t_count } for keys %t;',
map => 'my %t = %main::hosts; map { delete $t{$_} unless $t{$_} ==
+ $main::t_count } keys %t;',
or => 'my %t = %main::hosts; $t{$_} == $main::t_count or delete $
+t{$_} for keys %t;',
slice => 'my %t = %main::hosts; delete @t{ grep { $t{$_} != $main::t
+_count } keys %t };',
copy => 'my %t = %main::hosts; %t = map { $t{$_} == $main::t_count
+? ($_, $t{$_}) : ()} keys %t;',
nada => 'my %t = %main::hosts;'
});
And here's the output I get:
Rate copy map or do slice nada
copy 1372/s -- -57% -57% -57% -58% -78%
map 3175/s 131% -- -2% -2% -2% -50%
or 3226/s 135% 2% -- 0% -0% -49%
do 3226/s 135% 2% 0% -- -0% -49%
slice 3236/s 136% 2% 0% 0% -- -49%
nada 6289/s 358% 98% 95% 95% 94% --
"nada" is just there to identify how much time we're wasting making a fresh copy of the hash on each iteration.
As you can see, all of the approaches except for the copy one are so close that they're probably within the margin of error. Use the one that seems most legible, and if there's a risk that it won't be comprehended, encapsulate by wrapping it in a well-named subroutine.
-
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.