Most of the switch structures used in Perl scale linearly. They're all pretty much the same. The only exception to this is a hash that stores references to subroutines (example on page 282 of the Blue Camel).

As pg recently pointed out, hashes have an absolute worst case runtime of O(n), but that case is so unlikely that it can be safely ignored (and perl's specific implementation does tricks to help make sure it won't happen). In the common case, hashes run very close to O(1).

Note, though, that the constant value of hash searching is larger than a simple if tree, so if you have a small number of cases, the ifs might still be faster. If you're comparing integer, you could use a regular array instead of a hash, which will always give you O(1) efficiency with a much smaller constant.

----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer

: () { :|:& };:

Note: All code is untested, unless otherwise stated


In reply to Re: What is the most efficient perl switch/case statement? by hardburn
in thread What is the most efficient perl switch/case statement? by synistar

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.