For me, anyway, the goal is not always the absolute fastest performance possible (if it were, maybe I would write more programs in C). In this case, all else being equal, I would probably use sprintf over substr. I think that's mostly because the code is easier for me to understand at a glance. When I come back to this snippet of code a few months from now, it will take me longer to understand what the substr is doing.

Also, sprintf has functionality specifically intended for what we're using it for. It seems like we have to play with substr a little bit to get it to do what we need it to. If we have to use this code more than once, we'll either have to remember how we massaged substr and do it the exact same way again, or else put the substr solution in a subroutine of its own. Which is fine, but a little more effort.

To me anyway, the substr hoops are a little too large for me to jump through for a mere 2-3% gain in performance. But it could easily be that there are performance-critical applications for which the substr solution would be appropriate.

-- Mike

--
just,my${.02}


In reply to Re: sprintf vs. substr (for zero-padded values) by thelenm
in thread sprintf vs. substr (for zero-padded values) by Theseus

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.