in reply to How to access a static hash.
is just a lot more legible, intelligible, and therefor more maintainable thanmy $hash = { a => 'b' }; $hash->{$x}
and in terms of programmer time (as opposed to execution time), the former could be a time saver overall. That's probably a matter of personal judgment and taste, but I'd be inclined to agree with it. Especially as you get into larger numbers of hash elements, IMO, keeping the initialization and the fetching of a value as separate statements seems easier and more intuitive, somehow.{a => 'b'}->{$x}
Still, now that I've seen the latter idiom (no, I hadn't seen that sort of usage before), I can appreciate its attraction -- it's sort of like a clever substitute for the (chain of) ternary operator(s). Instead of this:
there's this:sub some_function { my ( $x ) = @_; return ( $x eq 'foo' ) ? "results for foo" : ( $x eq 'bar' ) ? "results for bar" : ( $x eq 'qaz' ) ? "results for qaz" : " ... and so on, ad nauseum"; }
It might be interesting to benchmark those alternatives, since they seem more "equivalent" (in terms of purpose) than the two you tested.sub some_function { my ( $x ) = @_; { foo => "results for foo", bar => "results for bar", qaz => "results for qaz", }->{$x} || "... and so on, ad nauseum"; }
(updated to fix a typo, and to add the following benchmark script:)
#!/usr/bin/perl use strict; use Benchmark qw(:all); sub anonhash { my ( $x ) = @_; { foo => "results for foo", bar => "results for bar", qaz => "results for qaz", }->{$x} || "... and so on, ad nauseum"; } sub ternary { my ( $x ) = @_; return ( $x eq 'foo' ) ? "results for foo" : ( $x eq 'bar' ) ? "results for bar" : ( $x eq 'qaz' ) ? "results for qaz" : " ... and so on, ad nauseum"; } my @strings = qw/foo bar baz qaz/; my $i = 0; cmpthese( -5, { anonhash => sub { anonhash( $strings[$i++] ); $i = 0 if ( $i == @strings ) }, ternary => sub { ternary( $strings[$i++] ); $i = 0 if ( $i == @strings ) }, } );
Rate anonhash ternary anonhash 64869/s -- -72% ternary 232475/s 258% --
Well, so much for being clever, I guess. ;)
One last update: I was still curious about "scalability": what happens as more distinct cases are needed? I adjusted my benchmark script by adding seven more hash keys to the anonhash function, and an equivalent set of seven more chained conditionals in the ternary function. Results:
Rate anonhash ternary anonhash 26893/s -- -87% ternary 204817/s 662% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to access a static hash.
by gam3 (Curate) on Mar 18, 2007 at 16:49 UTC |