in reply to How to access a static hash.

You're not testing what you claim you're testing: you're testing creating and accessing an an anonymous hash vs only accessing a named hash. You're also reading the result the wrong way 'round.

use strict; use warnings; use Benchmark qw(cmpthese); cmpthese(-10, { 'anon' => sub { for my $x (qw(a b a b a b)) { my $y = { 'a' => 'A' +, 'b' => 'B'}->{$x}; }}, 'named' => sub { for my $x (qw(a b a b a b)) { my $h = { 'a' => 'A +', 'b' => 'B'}; my $y = $h->{$x}; }}, });
output:
Rate named anon named 78120/s -- -8% anon 84539/s 8% --
Meaning that using an anonymous (not stored) hash is just a bit faster. Not very interesting, considering you almost always want to reuse a hash you've just created.

Replies are listed 'Best First'.
Re^2: How to access a static hash.
by gam3 (Curate) on Mar 17, 2007 at 20:33 UTC
    I was testing what I thought I was testing. What I don't understand is why Perl can't or doesn't optimize this case.
    Now if only I can learn to read the output of Benchmark.
    -- gam3
    A picture is worth a thousand words, but takes 200K.
      Ok, then I misunderstood your first code snippet.

      Note that the hash creation/deletion can only be optimized away if the content of the hash is constant (ie it would require extra analyzing code). I would guess it's possible to optimize it, but I don't think your construct is widely used (it's also fairly limited, since you can only access the hash once before it goes out of scope), so it probably won't really solve any "real-world" performance issues.

      As for the Benchmark output, I always find the "Rate - XXXX/s" results the easiest to interpret: those are just the number of calls completed per second, so higher is faster.