开发者

Performance and practice of lazy regex?

I read on the internet i should avoid lazy regex because of 'worse' performance and 'bad' practice. I never seen an example of either. I havent heard of an app that is CPU bound by its regular expression. Others say they 'learned' to avoid it but never mention why while one hinted it was because of usual side affects when turning on or off flags in 开发者_JAVA技巧older programs.

Are there a reasons to avoid lazy regex? If so what are they?


One thing you should try to ensure with any regular expression is that there's only one way for it to match a given match. That sounds weird, but there's an excellent article that demonstrates the point here... http://www.regular-expressions.info/catastrophic.html

It's rare that you'll encounter this degree of catastrophic backtracking as illustrated in this article. But just in case, it's a good idea to run a simple benchmark whenever writing a regular expression that'll see heavy use.


It depends on your target audience.

If you don't care about optimization, don't have high traffic and so on, it probably won't make a difference, and a lot of other optimization techniques that get you an extra 1/4 of a second won't either.

Lazy regex can take a lot more time performance-wise, but you may not notice that performance boost unless you're dealing with thousands of lines that its searching through or being done repetitively on a page.


Your regex should fit your problem. I have seen cases where a lazy regex performed significantly worse than a greedy regex, as well as the other way around. There is no universally "better" way to do it. Most important is that the regex returns the expected results. After you get that down, you can tweak it for speed and profile the different versions to get an accurate speed comparison.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜