简体   繁体   English

C#中Regex.Match的静态版本与实例版本

[英]static vs. instance versions of Regex.Match in C#

I've noticed some code that uses the static method: 我注意到一些使用静态方法的代码:

Regex.IsMatch([someRegexStr], [someInputStr])

Is it worth replacing it with the instance method? 是否值得用实例方法替换它? Like: 喜欢:

private readonly Regex myRegex = new Regex([someRegexStr]);

...

myRegex.IsMatch([someInputStr]);

One of the regular expression optimization recommendations in the following link: Regular Expression Optimization by Jim Mischel 以下链接中的正则表达式优化建议之一: Jim Mischel的 正则表达式优化

For better performance on commonly used regular expressions, construct a Regex object and call its instance methods. 为了在常用的正则表达式上获得更好的性能,请构造一个Regex对象并调用其实例方法。

The article contains interesting topics such as caching regular expressions and compiling regular expressions along with optimization recommendations. 本文包含一些有趣的主题,例如缓存正则表达式和编译正则表达式以及优化建议。

There is some initial processing that happens when you call the static Regex.IsMatch() method - essentially to validate your regular expression and convert it into a finite state machine representation. 调用静态Regex.IsMatch()方法时会发生一些初始处理 - 主要是验证正则表达式并将其转换为有限状态机表示。

If you plan on running the same regex match multiple times, you are probably better off instantiating a Regex instance, and calling the instance IsMatch() method. 如果您计划多次运行相同的正则表达式匹配,则最好实例化Regex实例,并调用实例IsMatch()方法。 You can have the epxression compiled into CLR bytecode using the RegexOptions.Compiled flag, which improves performance even more. 您可以使用RegexOptions.Compiled标志将epxression编译为CLR字节码,从而进一步提高性能。

The last 15 regular expression internal representations created from the static call are cached. 从静态调用创建的最后15个正则表达式内部表示被缓存。

I talk about this and the internal workings in " How .NET Regular Expressions Really Work ." 我在谈论这个以及“ .NET正则表达式如何真正起作用”中的内部工作

Yes, especially if you can make it a compiled expression. 是的,特别是如果你可以使它成为一个编译表达式。 It's slower to construct the Regex object this way, but much faster to use for a net win. 以这种方式构造Regex对象的速度较慢,但​​用于获胜的速度要快得多。

Edit: Potentially (probably++) much faster. 编辑:可能(可能是++)要快得多。 There's no requirement that the CLI have a good optimization, but I'm going to guess that Microsoft's certainly is. 没有要求CLI有一个很好的优化,但我猜测微软当然是。 :D :d

private readonly Regex myRegex = new Regex([someRegexStr], RegexOptions.Compiled);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM