开发者

Why do some people say Regex is inefficient, and is it really that bad? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

So, I've heard some people say that Regular Expressions is extremely inefficient and slow (and开发者_JAVA技巧 I especially hear about it with regards to C#). Is it true that Regex is that slow and is it really as bad to use as they make it out to be?

If it is that slow, what should I use in its place in large scale applications?


So, I've heard some people say that Regular Expressions is extremely inefficient and slow

That's not true. At least it is not true in all cases. It's just that there might be more adapted tools for some tasks than regular expressions. But claiming something like this and drawing such conclusions is simply wrong. There are situations where regexes work perfectly fine.


You will have to use it appropriately. It should not be the case of if all you have is a hammer, everything looks like a nail

Regexes are heavy weight and powerful and do have performance impact. You should not use for simple operations where say, string operations like substring would have sufficed. And you should not use them for very complicated stuff, as you get both performance and more importantly, readability hits.

And you should definitely not try to use regex for xml, html etc and use the appropriate parsers.

Bottomline: It is a tool. Have it in your toolkit, and use it appropriately.


Regular expressions are not as efficient as other techniques that are appropriate for specific situations.

However, that doesn't mean that one should not use them. If they provide adequate performance for your particular application, then using them is fine. If your application's performance is inadequate, do some testing to determine the cause of the problem rather than just eliminating all the regexes.

Also, there are smart ways to use regexes. For example, if you are doing the same operation a lot, then cache and reuse the regular expression object rather than recreating it every time it is used.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜