Another thing to try is to interleave duplicate tests so that start-up "settling in" doesn't scew the results:

use Benchmark qw( cmpthese ); cmpthese( @ARGV ? $ARGV[0] : -3, { Atr => sub { $string = "blah+blah+blah"; $string =~ tr/+/ /; }, As => sub { $string =~ "blah+blah+blah"; $string =~ s/\+/ /g; }, Btr => sub { $string = "blah+blah+blah"; $string =~ tr/+/ /; }, Bs => sub { $string =~ "blah+blah+blah"; $string =~ s/\+/ /g; }, });
which gave me these results:
Rate Atr Btr Bs As Atr 696801/s -- -2% -13% -45% Btr 711990/s 2% -- -11% -44% Bs 800289/s 15% 12% -- -37% As 1260797/s 81% 77% 58% --

Which (update doesn't) show tr to be faster than s but only slightly so. The fact is that the speed difference between s and tr is trivial for such cases. If you have really long strings, then tr becomes more attractive. But when tr really becomes attractive is when you want to replace lots of different characters with lots of different characters. For example, write a ROT13 encoder with s and you'll see what I mean.

Update: Sorry, I read the numbers backward. Not that it matters much to me as I don't really care whether I can do 0.7 million per second or 1.2 million per second. (: The point is that they are both fast and fairly close to each other in speed. Thanks to petral for pointing my mistake out to me.

Swapping out s for tr for this case is really another case of premature optimization. But making the choice of using tr in the beginning for this case is probably good defensive programming. (:

        - tye (but my friends call me "Tye")

In reply to (tye)Re: transliterate by tye
in thread transliterate by Anonymous Monk

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.