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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.