Regex.IsMatch VS string.ContainsIsMatch、Regex、VS、Contains

2023-09-02 10:26:54 作者:未来会有我骄傲的存在

有没有在速度/内存使用,这两个相当于前pressions任何区别:

Is there any difference in speed/memory usage for these two equivalent expressions:

Regex.IsMatch(Message, "1000")

VS

Message.Contains("1000")

在任何情况下,一个是比其他更好吗?

Any situations where one is better than other ?

这个问题的背景下是如下: 我正在其中包含的正则表达式EX pression找到一个字符串是否包含另一个字符串中的一些改变,传统的code。作为传统的code我没有做任何更改,并在code回顾有人建议,Regex.IsMatch应string.Contains更换。所以我想知道是否改变是值得的。

The context of this question is as follows: I was making some changes to legacy code which contained the Regex expression to find whether a string is contained within another string. Being legacy code I did not make any changes to that and in the code review somebody suggested that Regex.IsMatch should be replaced by string.Contains. So I was wondering whether the change was worth making.

推荐答案

对于简单的情况下, String.Contains 会给你更好的性能,但字符串。含不会允许你做复杂的模式匹配。使用 String.Contains 非模式匹配的情况(像在您的示例),并使用正则EX pressions的情况下,您需要做的更复杂的图案匹配。

For simple cases String.Contains will give you better performance but String.Contains will not allow you to do complex pattern matching. Use String.Contains for non-pattern matching scenarios (like the one in your example) and use regular expressions for scenarios in which you need to do more complex pattern matching.

一个普通EX pression有与它(如pression分析,编译,执行等),像一个简单的方法 String.Contains 根本没有这也就是为什么 String.Contains 将超越常规的前pression在你们这样的例子。

A regular expression has a certain amount of overhead associated with it (expression parsing, compilation, execution, etc.) that a simple method like String.Contains simply does not have which is why String.Contains will outperform a regular expression in examples like yours.