【问题标题】:Performance issues with Regex class inside a loop循环内正则表达式类的性能问题
【发布时间】:2011-05-15 23:21:04
【问题描述】:

我有一个数据表,其中包含两列(pattern 和 neworder)和 cca 100 行(都具有不同的模式)。

我正在做的是将输入字符串与模式匹配(分组匹配),如果发生匹配,我想使用 Regex.Replace 命令重新排列检索到的组。

问题是正则表达式在循环中使用时表现得不是很友好。由于我必须将输入字符串与多个模式匹配,并重新排列输出字符串的外观,因此我完成此任务的唯一方法是使用 Regex 类。但这看起来不是一个合适的解决方案,因为它会显着降低性能。

代码如下所示

DataTable dt = this.GetPatterns();
DataRow dr;
System.Collections.IEnumerator ie = dt.Rows.GetEnumerator();
while(ie.MoveNext() && !found)
{
    dr = ((DataRow)ie.Current);
    pattern = dr["pattern"].ToString();
    neworder= dr["neworder"].ToString();

    Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
    Match match = reg.Match(input_string);

    if (match.Success)
    {
    found = true;
    output = reg.Replace(input_string, neworder);
    }

}

【问题讨论】:

    标签: .net regex performance memory-leaks


    【解决方案1】:

    如果您使用静态方法进行匹配,.NET 会自动为您缓存已编译的 Regex 对象。

    if (Regex.Match(input, pattern, options).Success)
    {
      output = Regex.Replace(input, pattern, neworder, options);
    }
    

    默认情况下它只缓存最近使用的 15 个对象,因此您需要通过调整 Regex.CacheSize 属性来增加它。

    【讨论】:

    • 不,你的建议是有道理的,但它对我不起作用。我添加了 Regex.CacheSize = 200,但我最终遇到了同样的问题。我什至尝试创建一个 Regex 对象数组,这样我就不必再次重用相同的对象,但这也没有帮助。
    • 我突然想到if (Match) 步骤是多余的,因为这实际上是Replace 方法所做的第一件事。但是,如果您删除该步骤并且性能仍然无法接受,您将不得不单独调整正则表达式,或者重新设计应用程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多