Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: elsif chain vs. dispatch

by chromatic (Archbishop)
on Apr 26, 2009 at 22:59 UTC ( #760215=note: print w/ replies, xml ) Need Help??


in reply to elsif chain vs. dispatch

Even though looking up an element of a hash tends to be an O(1) operation, its algorithmic complexity only describes the scaling factor of the algorithm as n increases. If you rearranged the if/else branches in decreasing order of probability according to your expected corpus, it would be faster than the hash lookup until you reached (wild guess) a dozen or so entries in the hash, or if your working corpus deviated significantly from your expected corpus.

A good benchmark with working example data would reveal more, but remember that:

  • This depends on your version of Perl, your workload, and your machine.
  • Getting the best performance possible is a matter of tuning.
  • Perl is sensitive to fluctuations between different optrees and working sets.
  • This is unlikely a bottleneck in any meaningful application.


Comment on Re: elsif chain vs. dispatch
Select or Download Code
Re^2: elsif chain vs. dispatch
by sflitman (Hermit) on Apr 26, 2009 at 23:50 UTC
    For me, it is that the codebase is becoming unwieldy, so I wanted to switch to the dispatch style, and I was (honest) going to be putting it outside a sub so it only gets compiled once!

    Have you ever considered using the symbol table as the hash, would this be any good:

    $::{"handle_fieldcode_$code"}->($args); # for $code = 'A'..'Z'
    ??
    SSF

      The slow bit is the function call, not the hash lookup which you'd also have to do with the symtab anyway. With a hash, you have better control over what inputs are allowed and how they are dispatched.

      With symtab:

      my $handler = do { no strict 'refs'; \&{"handle_fieldcode_$code"} }; ...handle expections somehow?... die if !$handler; $handler->(@args);

      With hash;

      my $handler = $lookup{$code}; die if !$handler; $handler->(@args);

      with a one-time setup of

      my %lookup = map { no warnings 'refs'; $_ => \&{"handle_fieldcode_$_"} } 'A'..'Z'; ...modify %lookup for expections...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2015-07-04 21:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls