foreach my $key (@_) {
$hr = $hr->{$key} ||= {};
};
####
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
use Benchmark qw(cmpthese);
my $hash = {};
set_hash( $hash, 42, qw(foo bar baz x y z t) );
print Dumper( $hash );
my $hash_foreach = {};
set_hash_foreach( $hash_foreach, 42, qw(foo bar baz x y z t) );
my $hash_exists = {};
set_hash_exists( $hash_exists, 42, qw(foo bar baz x y z t) );
Dumper($hash_foreach) eq Dumper($hash) or die "hash_foreach inconsistent";
Dumper($hash_exists) eq Dumper($hash) or die "hash_exists inconsistent";
cmpthese ( -1, {
while => sub {
for (1..10000) {
set_hash( {}, 42, qw(foo bar baz x y z t) );
};
},
foreach => sub {
for (1..10000) {
set_hash_foreach( {}, 42, qw(foo bar baz x y z t) );
};
},
exists => sub {
for (1..10000) {
set_hash_exists( {}, 42, qw(foo bar baz x y z t) );
};
},
});
sub set_hash {
my $hr = shift;
my $val = shift;
my $last_key = pop;
while (@_) {
my $key = shift;
$hr->{$key} = {} if ! exists $hr->{$key};
$hr = $hr->{$key};
}
$hr->{$last_key} = $val;
};
sub set_hash_foreach {
my $hash = shift;
my $value = shift;
my $last_key = pop;
foreach my $k (@_) {
$hash = $hash->{$k} ||= {};
};
$hash->{$last_key} = $value;
};
sub set_hash_exists {
my $hr = shift;
my $val = shift;
my $last_key = pop;
foreach my $key (@_) {
$hr->{$key} = {} if ! exists $hr->{$key};
$hr = $hr->{$key};
}
$hr->{$last_key} = $val;
};
####
$VAR1 = {
'foo' => {
'bar' => {
'baz' => {
'x' => {
'y' => {
'z' => {
't' => 42
}
}
}
}
}
}
};
Rate while exists foreach
while 21.3/s -- -10% -21%
exists 23.6/s 11% -- -12%
foreach 27.0/s 27% 14% --