Here's my benchmark:
use Benchmark 'cmpthese';
use strict;
my %hash = 1 .. 10_000;
my %add = 9_001 .. 11_000;
cmpthese(-5, {
BASE => sub {
my %copy = %hash;
},
JAPHY => sub {
my %copy = %hash;
my @new = grep !exists $copy{$_}, keys %add;
@copy{@new} = @add{@new};
},
ZAXO => sub {
my %copy = %hash;
%copy = (%add, %copy);
},
NULL => sub {
my %copy = %hash;
%copy = (%copy);
},
});
Here are the results I get:
Rate ZAXO NULL JAPHY BASE
ZAXO 15.1/s -- -22% -61% -76%
NULL 19.3/s 28% -- -50% -69%
JAPHY 38.9/s 157% 101% -- -38%
BASE 62.4/s 312% 223% 60% --
The two cases 'BASE' and 'NULL' show that Perl does not optimize
%hash = %hash at all, since 'NULL' is three times slower than 'BASE'. 'JAPHY' is 2.5 times faster than 'ZAXO' in this run, with 500 old keys and 500 new keys. When I change %add to be (5_001 .. 12_000), the run times are:
Rate ZAXO NULL JAPHY BASE
ZAXO 11.4/s -- -39% -58% -81%
NULL 18.6/s 63% -- -31% -69%
JAPHY 26.9/s 136% 45% -- -56%
BASE 60.5/s 431% 225% 125% --
The point is that
%a = (%b, %a) is slow because it is O(N+M) where N is the size of %a and M is the size of %b. My code is O(M) -- specifically, O(M(1+x)) where x is the fraction of keys in %b that aren't in %a -- because it doesn't iterate over %a at all, only %b.
_____________________________________________________
Jeff
japhy Pinyan,
P.L., P.M., P.O.D, X.S.:
Perl,
regex,
and
perl
hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
-
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.