in reply to Re: Setting a multi-dimensional hash value
in thread Setting a multi-dimensional hash value
I did a quick benchmark and it looks like it's also faster:foreach my $key (@_) { $hr = $hr->{$key} ||= {}; };
I thought exists would benefit over a ||=, but it looks like it doesn't:#!/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 inconsiste +nt"; 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; };
Still I ++ your answer.$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% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Setting a multi-dimensional hash value
by roboticus (Chancellor) on Apr 30, 2015 at 13:05 UTC |