Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: How to access a static hash.

by ferreira (Chaplain)
on Mar 17, 2007 at 18:19 UTC ( [id://605292]=note: print w/replies, xml ) Need Help??


in reply to How to access a static hash.

I think you are making a mistake. The surprising hypothesis you are testing is whether the access to a literal hash ref

{ a => 'b' }->{$k};
is slower than saving the hash ref in a var and accessing
my $hash_ref = { a => 'b' }; # and then $hash_ref->{$k}
And your benchmark suggested it is so indeed. I guess you're wondering: but there should be an overhead to access the variable, so that using a var should be slower. But the big problem with your benchmark code is that the literal hash ref is being constructed inside the loop over and over, and that causes an overhead greater than the one of acessing the variable.

I think the hypothesis "access to a literal hash ref is slower than access via a hash ref saved in a variable" is not true. The following code adds a more fair alternative with a constant to save the literal (so that is not built over and over inside the loop) and you'll see that this is the fastest option.

Another alternative using a lexical variable (my) instead of package variable (our) was introduced as well. But there is no visible performance difference in this case.

use strict; use warnings; use Benchmark qw(cmpthese); our $global_hash = { 'a' => 'A', 'b' => 'B'}; my $lexical_hash = { 'a' => 'A', 'b' => 'B'}; use constant CONST_HASH => { 'a' => 'A', 'b' => 'B'}; cmpthese(-2, { 'hash' => sub { for my $x (qw(a b a b a b)) { my $y = { 'a' => 'A' +, 'b' => 'B'}->{$x}; }}, 'global_ref' => sub { for my $x (qw(a b a b a b)) { my $y = $globa +l_hash->{$x}; }}, 'lexical_ref' => sub { for my $x (qw(a b a b a b)) { my $y = $lexi +cal_hash->{$x}; }}, 'const' => sub { for my $x (qw(a b a b a b)) { my $y = CONST_HASH( +)->{$x}; }}, });
and a sample result:
Rate hash global_ref lexical_ref const hash 27571/s -- -73% -74% -76% global_ref 102819/s 273% -- -3% -10% lexical_ref 105720/s 283% 3% -- -8% const 114361/s 315% 11% 8% --

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://605292]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-25 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found