In terms of performance, and maintenance, with a variable set of $type's mapping to a variable set of subroutines that need to be invoked, I would combine and enhance two of your approaches to be:

my %dispatch_table = ( 'apple' => [\&a, ...], 'orange' => [\&o, ...], ... ); while (defined($object = read one)) { $_->($object) for @{$dispatch_table{$type}}; }

This approach avoids using a large amount of memory up front to read all objects in to memory, and dispatches using a hash lookup, which will ensure that dispatching is far more linear in terms of number of possible $type values, than would be possible with a string of if, elsif, elsif, ... would be.

Another small trick that I employ above, is to use the suffix modifier form of the for() loop. Although in theory, for(){statement;} should be as fast as statement for();, it is not. The second does not use a block, and avoids some of the block overhead by using simpler op codes underneath.


In reply to Re: performance - loops, sub refs, symbol tables, and if/elses by MarkM
in thread performance - loops, sub refs, symbol tables, and if/elses by jaa

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.