【问题标题】:Create a faster regular expression clr function创建更快的正则表达式 clr 函数
【发布时间】:2013-01-02 23:54:06
【问题描述】:

我正在尝试改进链接 http://msdn.microsoft.com/en-us/magazine/cc163473.aspx 中的 Clr 功能。

public static partial class UserDefinedFunctions 
{
    public static readonly RegexOptions Options =
        RegexOptions.IgnorePatternWhitespace |
        RegexOptions.Singleline;

    [SqlFunction]
    public static SqlBoolean RegexMatch(
        SqlChars input, SqlString pattern)
    {
        Regex regex = new Regex( pattern.Value, Options );
        return regex.IsMatch( new string( input.Value ) );
    }
}

执行select * from Table1 where dbo.RegexMatch(col1, 'pattern') = 1 时,Clr 函数为表中的每一行创建一个新的Regex 对象。

是否可以为每个 Sql 语句只创建一个 Regex 对象?对于每一行,只需致电regex.Ismatch(...)。下面的代码有效吗?

public static partial class UserDefinedFunctions 
{
    public static readonly RegexOptions Options =
        RegexOptions.IgnorePatternWhitespace |
        RegexOptions.Singleline;

    static Regex regex = null;

    [SqlFunction]
    public static SqlBoolean RegexMatch(
        SqlChars input, SqlString pattern)
    {
        if (regex == null) 
            regex = new Regex( pattern.Value, Options );
        return regex.IsMatch( new string( input.Value ) );
    }
}

【问题讨论】:

  • 文章建议如果你使用RegexOptions.Compiled,那么它可能会被缓存——但我看不到任何其他证据......
  • 有趣。 Regex 的构造函数将重用 Regex 实例,如果它具有已编译的选项和相同的模式?我在想一些单例模式,但不确定单例的寿命。
  • 它不会重用相同的实际实例,但它可以重用所有已完成的工作来创建前一个实例。
  • 您只是将竞争条件放入 SQL Server 并破坏了它的可靠性。并发查询将在彼此的正则表达式上乱写。这就是它被禁止的原因。 (有解决方法。)
  • msdn 链接已失效。

标签: c# sql-server sql-server-2008 sql-server-2005 sqlclr


【解决方案1】:

你的静态正则表达式的基于 UDF 的实例可能甚至没有被重复使用,你最好调用静态版本

System.Text.RegularExpressions.RegEx.IsMatch(string input, string pattern, RegexOptions options);

直接。

请注意,调试模式下的工作方式与生产环境下的工作方式不同,并且 SQL 会在需要时释放内存。

另外,请尝试使用RegexOptions.CompiledCultureInvariant

【讨论】:

  • 静态重载在后台使用缓存,这就是为什么这个答案很好。 +1
  • 奇怪为什么静态只读方法甚至不能被重用?
猜你喜欢
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2012-01-02
  • 2010-10-01
  • 1970-01-01
  • 2018-10-06
  • 2011-11-09
  • 1970-01-01
相关资源
最近更新 更多