You've created a benchmark where the cost of compiling a single regex containing 45000 alternations is overwhelmingly more expensive than running that compiled regex 11 times.

In the qr case, the pattern is compiled once, *before* the benchmark is run. The benchmark cost is 11 matches, plus 11 clonings of the compiled regex's internal struture.

In the str case, the benchmark includes compiling the pattern before matching the first word. For the subsequent 10 matches it attempt to recompile /$str/, but each time it uses an optimisation where it sees if the string has changed since last time and if so skips recompiling it.

So sometimes /$str/ in a loop for unchanging $str can be faster than /$qr/, but that benchmark won't show it.

Or more formally, if C is the time to compile a pattern, M is the time to run (match) against the compiled pattern, and D is the time to duplicate the regex structure, then

$qr = /.../; /$qr/ for 1.N
takes C + N(M+D), but your benchmark was measuring N(M+D); while
$str = "..."; /$str/ for 1.N
takes N(C+M) C + NM, which was what your benchmark was measuring. (I just corrected the above - I forgot to include the 'unchanged pattern' optimisation)

Dave.


In reply to Re^5: Performance penalty of using qr// by dave_the_m
in thread Performance penalty of using qr// by Athanasius

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.