http://qs321.pair.com?node_id=1205999


in reply to Re^4: Performance penalty of using qr//
in thread Performance penalty of using qr//

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.