确保字符串不包含特定字符的快速方法

EOG*_*EOG 4 c# string validation performance

我想确保 C# 字符串不包含特定字符。

我正在使用string.IndexOfAny(char[]),在我看来,Regex 在这项任务中会比较慢。有没有更好的方法来实现这一点?速度在我的应用程序中至关重要。

Kam*_*ami 5

IndexOfvs IndexOfAnyvs Regexvs进行快速基准测试Hashset
500 字 lorem ipsum haystack,带两个字针。
在干草堆中使用两根针进行测试,在干草堆中使用一根针,在干草堆中均未进行测试。

    private long TestIndexOf(string haystack, char[] needles)
    {
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        for (int i = 0; i < 1000000; i++)
        {
            int x = haystack.IndexOfAny(needles);
        }
        sw.Stop();

        return sw.ElapsedMilliseconds;
    }

    private long TestRegex(string haystack, char[] needles)
    {
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        Regex regex = new Regex(string.Join("|", needles));
        for (int i = 0; i < 1000000; i++)
        {
            Match m = regex.Match(haystack);
        }
        sw.Stop();

        return sw.ElapsedMilliseconds;
    }

    private long TestIndexOf(string haystack, char[] needles)
    {
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        for (int i = 0; i < 1000000; i++)
        {
            int x = haystack.IndexOf(needles[0]);
        }
        sw.Stop();

        return sw.ElapsedMilliseconds;
    }

    private long TestHashset(string haystack, char[] needles)
    {
        HashSet<char> specificChars = new HashSet<char>(needles.ToList());
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        for (int i = 0; i < 1000000; i++)
        {
            bool notContainsSpecificChars = !haystack.Any(specificChars.Contains);
        }
        sw.Stop();

        return sw.ElapsedMilliseconds;
    }
Run Code Online (Sandbox Code Playgroud)

1,000,000 次迭代的结果:

索引:28/2718/2711 任意
索引:153/141/17561 正则
表达式:1068/1102/92324
哈希集:939/891/111702

笔记:

  • 较小的干草堆可以提高性能。
  • 较大的针组可提高正则表达式的性能。
  • 较大的针组会降低任何性能指标。
  • 如果needle不在大海捞针中,所有方法的性能都会下降

总体而言,根据干草堆和针的大小,最多regex会慢indexofany10 倍。