Long time passing - but here are some better benchmarks that are rather interesting...
use Benchmark qw(timethese cmpthese countit timestr);
my $hash1 = {
one => 'One',
two => 'One',
three => 'One',
four => 'One',
five => 'One',
};
my $hash2 = {
one => 'One',
four => 'One',
five => 'One',
};
my $hash3 = {};
for (0..1000) { $hash3->{"foo_$_"} = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aa" }
cmpthese (-2,{
forloop => sub {
my $hash = {};
foreach my $foo ($hash1, $hash2, $hash3) {
foreach my $key (keys %$foo) {
$hash->{$key} = $foo->{$key} if ! exists $hash->{$key};
}
}
},
forloop2 => sub {
my $hash = {};
foreach my $foo ($hash3, $hash2, $hash1) {
foreach my $key (keys %$foo) {
$hash->{$key} = $foo->{$key};
}
}
},
whileloop => sub {
my $hash = {};
foreach my $foo ($hash1, $hash2, $hash3) {
while (my($key, $val) = each %$foo) {
$hash->{$key} = $val if ! exists $hash->{$key};
}
}
},
whileloop2 => sub {
my $hash = {};
foreach my $foo ($hash3, $hash2, $hash1) {
while (my($key, $val) = each %$foo) {
$hash->{$key} = $val;
}
}
},
slice => sub {
my $hash = {};
foreach my $foo ($hash3, $hash2, $hash1) {
@$hash{keys %$foo} = values %$foo;
}
},
merge => sub {
my $hash = {%$hash3, %$hash2, %$hash1};
},
},'auto');
Which produce the following (for our box anyway)...
Benchmark: running forloop, forloop2, merge, slice, whileloop, whilelo
+op2, each for at least 2 CPU seconds...
forloop: 3 wallclock secs ( 2.22 usr + 0.00 sys = 2.22 CPU) @ 10
+8.11/s (n=240)
forloop2: 2 wallclock secs ( 2.09 usr + 0.01 sys = 2.10 CPU) @ 12
+2.38/s (n=257)
merge: 2 wallclock secs ( 2.10 usr + 0.00 sys = 2.10 CPU) @ 17
+6.19/s (n=370)
slice: 2 wallclock secs ( 2.14 usr + 0.00 sys = 2.14 CPU) @ 14
+0.19/s (n=300)
whileloop: 2 wallclock secs ( 2.16 usr + 0.00 sys = 2.16 CPU) @ 87
+.04/s (n=188)
whileloop2: 2 wallclock secs ( 2.07 usr + 0.01 sys = 2.08 CPU) @ 11
+0.10/s (n=229)
Rate whileloop forloop whileloop2 forloop2 slice
+ merge
whileloop 87.0/s -- -19% -21% -29% -38%
+ -51%
forloop 108/s 24% -- -2% -12% -23%
+ -39%
whileloop2 110/s 26% 2% -- -10% -21%
+ -38%
forloop2 122/s 41% 13% 11% -- -13%
+ -31%
slice 140/s 61% 30% 27% 15% --
+ -20%
merge 176/s 102% 63% 60% 44% 26%
+ --
As for memory - with a 0..1 on the hash3, we used 4 k less memory for the merge. On a 0..10000 on the hash3 we used 300k more (1.5M vs 1.2M) for the merge. Merge is definitely the fastest way - without "too much" memory overhead.
my @a=qw(random brilliant braindead); print $a[rand(@a)];
|