Yeah, but I don't like it. I don't like assigning X to itself like the example does. I'd prefer a slightly long-winded approach:
$hash{$_} = $otherhash{$_} for grep !exists $hash{$_}, keys %otherhash
+;
Or:
{
my @new_keys = grep !exists $hash{$_}, keys %otherhash;
@hash{@new_keys} = @otherhash{@new_keys};
}
_____________________________________________________
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
| [reply] [Watch: Dir/Any] [d/l] [select] |
| [reply] [Watch: Dir/Any] |
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
| [reply] [Watch: Dir/Any] [d/l] [select] |