I'm looking for some places I can squeeze a little bit more performance out of a sub. dprof says this sub is running 50% of the time for my application, so it looks like my best candidate for optimization.
# Print the given template sections to the supplied filehandle sub printto { my $self = shift; my $fh = shift; my $ret = 0; my($val,$sec,$v); for(;@_;shift) { $sec = $self->[_sec]{$_[0]}; if (!defined($sec)) { print $fh $self->_nosuchsec($_[0]); next; } $ret++; foreach $v (@$sec) { if ($v->[_type] == type_text) { print $fh $v->[_contents]; } else { $val = $self->[_assign]{$v->[_contents]}; print $fh defined($val) ? $val : $self->_nosuchvar($val,"\$".$val); } } } $ret; }
This is the output routine for a templating engine. It takes as parameters an object, a filehandle, and zero or more template section names to display. For each template section name, if the section exists it displays all parts of it. A part is either plain text, or else a variable; variables are looked up in the $self->[_assign] hashref. The _nosuchsec and _nosuchvar routines are error handlers, and are never called in normal operation.

Here's what DProf says:

%Time ExclSec CumulS #Calls sec/call Csec/c  Name
 51.9   21.53 21.280 130000   0.0002 0.0002  FTS::printto

Any ideas where to look for that last little bit of performance?

Thanks!


In reply to Optimizing the bejeezus out of a sub by sgifford

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.