Why is my regex so much slower compiled than interpreted?

前端 未结 5 882
花落未央
花落未央 2021-02-18 18:17

I have a large and complex C# regex that runs OK when interpreted, but is a bit slow. I\'m trying to speed this up by setting RegexOptions.Compiled, and this seems

5条回答
  •  迷失自我
    2021-02-18 19:13

    When using RegexOptions.Compiled, you should make sure to re-use the Regex object. It doesn't seem like you are doing this.

    RegexOptions.Compiled is a trade-off. The initial construction of the Regex will be slower, because code is compiled on-the-fly, but each match should be faster. If your regular expression changes at run-time, there will probably be no benefit from using RegexOptions.Compiled, although it might depend on the actual expression involved.

    Update, per the comments

    If your actual code looks like the one you have posted, you are not taking any advantage of CompileToAssembly, as you are creating new, on-the-fly compiled instances of Regex each time that piece of code runs. In order to take advantage of CompileToAssembly, you will need to compile the Regex first; then take the generated assembly and reference it in your project. You should then instantiate the generated, strongly-typed Regex types generated.

    In the example you link to, he has a regular expression named FindTCPIP, which gets compiled into a type named FindCTPIP. When this needs to be used, one should create a new instance of this specific type, such as:

    TheRegularExpressions.FindTCPIP MatchTCP = new TheRegularExpressions.FindTCPIP();
    

提交回复
热议问题