Cha*_*ion 1 c# regex performance jit threadpool
我一直在使用C#正则表达式,它在Web应用程序中被大量用作自定义模板系统的一部分.表达式很复杂,我注意到使用Regex.Compiled选项可以获得真正的性能提升.然而,编译的初始成本在开发期间是恼人的,特别是在迭代单元测试期间(这里提到了这种一般的权衡).
我目前正在尝试的一个解决方案是懒惰的正则表达式编译.我的想法是,我可以通过在一个单独的线程中创建一个正则表达式的编译版本并在准备就绪时将其打包来充分利用这两个世界.
我的问题是:有什么理由说这可能是一个糟糕的想法表现或其他?我问,因为我不确定是否分配跨线程的jitting和程序集加载之类的成本确实有效(尽管它似乎来自我的基准测试).这是代码:
public class LazyCompiledRegex
{
private volatile Regex _regex;
public LazyCompiledRegex(string pattern, RegexOptions options)
{
if (options.HasFlag(RegexOptions.Compiled)) { throw new ArgumentException("Compiled should not be specified!"); }
this._regex = new Regex(pattern, options);
ThreadPool.QueueUserWorkItem(_ =>
{
var compiled = new Regex(pattern, options | RegexOptions.Compiled);
// obviously, the count will never be null. However the point here is just to force an evaluation
// of the compiled regex so that the cost of loading and jitting the assembly is incurred here rather
// than on the thread doing real work
if (Equals(null, compiled.Matches("some random string").Count)) { throw new Exception("Should never get here"); }
Interlocked.Exchange(ref this._regex, compiled);
});
}
public Regex Value { get { return this._regex; } }
}
Run Code Online (Sandbox Code Playgroud)