Hmmm ... it seems to me that your benchmarks are actually indicating that tr/// is slower than s///. Not what I would have expected, and apparently no one else did either, since despite the evidence, everyone is claiming that this test shows that tr/// is faster.

Update: I just ran the benchmark on my ActiveState build and got similar results ... that, strangely, s appears to be nearly twice as fast as tr in this trivial example. Results showing only about 1 million tr's per second vs. almost 2 million s's per second:

Rate transliterate substitution transliterate 1011345/s -- -49% substitution 1969797/s 95% --

Just for background, this is ActivePerl 5.8.0 build 806.

UPDATE Update: Thanks to davido for pointing us in the right direction on this in the CB before he posted his node.

use Benchmark qw(:all); $toto = 'this+is+my+text+and+here+is+more+and+more+this+is+my+text+and ++here+is+more+and+more+this+is+my+text+and+here+is+more+and+more'; $count =-5; $results = timethese($count, { 'transliterate' => sub { $toto = 'this+is+my+text+and+ +here+is+more+and+more+this+is+my+text+and+here+is+more+and+more+this+ +is+my+text+and+here+is+more+and+more'; $toto =~tr/+/ /; }, 'substitution' => sub { $toto = 'this+is+my+text+and+h +ere+is+more+and+more+this+is+my+text+and+here+is+more+and+more+this+i +s+my+text+and+here+is+more+and+more'; $toto =~s/\+/ /g; }, }, 'none' ); cmpthese( $results ) ; exit 0;
Now we have the same string for the benchmark tests! And the results are as expected:
Rate substitution transliterate substitution 73807/s -- -88% transliterate 625256/s 747% --

Boy, do I feel stupid for not seeing that!


-HZ

In reply to Re: Re: Difference between tr// and s///? by HyperZonk
in thread Difference between tr/// and s///? by kalamiti

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.