|The stupid question is the question not asked|
Re^2: An optimization of last resort: eliminate capturing from your regexps (hit)by tye (Cardinal)
|on Jul 11, 2006 at 14:28 UTC||Need Help??|
Hopefully to be somewhat clearer, $`, $&, and $' are especially bad because once they've been seen by Perl, all regexes will do extra work.
Capturing in a regex imparts a performance hit because it means that a copy will be made of the string that the regex is being applied to (which makes it a worse performance hit when matching against really large strings -- one of the worst cases being running a lot of little regexes with capturing against the same huge string, something a parser is likely to do). The performance hit of capturing only applies to the regex that does capturing and most of the time it isn't enough that you'd notice.
@- and @+ are always set by regexes and whether you use them or not doesn't have any performance impact at all.
I'm curious why the regex engine doesn't just copy out the parts that were captured and only copy them after the regex has finished. That seems like a "best of both worlds" solution. Though, I think /k would be really cool, especially if you could use it with:
to make it so it doesn't matter whether $regex contained capturing parens or not. (:
Finally, this benchmark shows that the per-regex performance hit from $`, $&, and $' is the same hit from capturing parens:
But, remember: $`, $&, and $' are evil while capturing parens are usually the best solution when you need them and usually don't cause a noticeable performance penalty.