I've been benchmarking code all morning and this doesn't seem right. By itself
tr is slower than eq in comparing 13 character strings. I understand and
completely agree with that. What is strange to me is that tr is faster in a
loop than eq. The tr command in the eq loop should never execute. What's
happening?
use strict; use warnings; use Benchmark qw(cmpthese); my $string = '0'x13; cmpthese(0, { 'eq_loop' => q(for (0..12) { next if ($string eq '0000000000000'); $_ = ($string =~ tr/1/1/); }), 'tr_loop' => q(for (0..12) { next unless ($_ = ($string =~ tr/1/1/)); }), 'eq' => q($string eq '0000000000000';), 'tr' => q($string =~ tr/1/1/;), });

Benchmark: running eq, eq_loop, tr, tr_loop, each for at least 3 CPU seconds...
        eq:  4 wallclock secs ( 3.30 usr +  0.00 sys =  3.30 CPU) @ 1173221.21/s (n=3871630)
   eq_loop:  4 wallclock secs ( 3.00 usr +  0.00 sys =  3.00 CPU) @ 16577.00/s (n=49731)
        tr:  3 wallclock secs ( 3.08 usr +  0.00 sys =  3.08 CPU) @ 536228.57/s (n=1651584)
   tr_loop:  4 wallclock secs ( 3.17 usr +  0.00 sys =  3.17 CPU) @ 18796.53/s (n=59585)
             Rate eq_loop tr_loop      tr      eq
eq_loop   16577/s      --    -12%    -97%    -99%
tr_loop   18797/s     13%      --    -96%    -98%
tr       536229/s   3135%   2753%      --    -54%
eq      1173221/s   6977%   6142%    119%      --


In reply to tr faster than eq? by Keystroke

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.