my $hash = { a => 'b' }; $hash->{$x}
would be less confusing (no needless use of references) and less complicated (two fewer operations and one less variable) as
my %hash = ( a => 'b' ); $hash{$x}
It's also much faster.
Results:
hash vs hash ref: hash is 30-40% faster.
inline vs hash: hash is 30-40% faster.
global vs local hash: global is 600-700% faster. (Would be even faster if the hash had more elements.)
Benchmark code and numbers:
use strict; use warnings; use Benchmark qw( cmpthese ); { my $test_const_hr = q{ +my $e = $const_hr->{a}; }; my $test_const_hash = q{ +my $e = $const_hash{a}; }; my $test_built_hr = q{ my $built_hr = { a => 'A', b => 'B' }; +my $e = $built_hr->{a}; }; my $test_built_hash = q{ my %built_hash = ( a => 'A', b => 'B' ); +my $e = $built_hash{a}; }; my $test_inline_hr = q{ +my $e = { a => 'A', b => 'B' }->{a}; }; our $const_hr = { a => 'A', b => 'B' }; our %const_hash = ( a => 'A', b => 'B' ); $_ = 'use strict; use warnings; our $const_hr; our %const_hash; ' . + $_ for $test_const_hr, $test_const_hash, $test_built_hr, $test_built_hash, $test_inline_hr; cmpthese(-3, { const_hr => $test_const_hr, const_hash => $test_const_hash, built_hr => $test_built_hr, built_hash => $test_built_hash, inline_hr => $test_inline_hr, }); }
Rate inline_hr built_hr built_hash const_hr const +_hash inline_hr 209314/s -- -3% -27% -87% + -90% built_hr 216267/s 3% -- -24% -87% + -90% built_hash 285632/s 36% 32% -- -83% + -86% const_hr 1638207/s 683% 657% 474% -- + -22% const_hash 2103430/s 905% 873% 636% 28% + --
In reply to Re: How to access a static hash.
by ikegami
in thread How to access a static hash.
by gam3
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |