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

标签 c# string performance validation

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

我正在使用 string.IndexOfAny(char[]),我认为 Regex 在此任务中会更慢。有没有更好的方法来完成这个?速度在我的应用程序中至关重要。

最佳答案

IndexOf vs IndexOfAny vs Regex vs Hashset 进行快速基准测试。
500 字 lorem ipsum haystack,带有两个字符针。
在 haystack 中测试了两根针,在 haystack 中测试了一根针,在 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;
    }

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

Index of : 28/2718/2711
Index of Any : 153/141/17561
Regex of : 1068/1102/92324
Hashset : 939/891/111702

注意事项:

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

总体而言,regexindexofany 慢 10 倍,具体取决于干草堆和针的大小。

关于c# - 确保字符串不包含特定字符的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656724/

相关文章:

ruby - 字符串文字中的转义状态作为 `String#tr` 的参数

php - 用于确定函数返回的 if 语句的问题

java - Java 中的字符串子串生成

c# - 是否有任何简单的方法可以从内部将值分配给模型列表?

C# 系统 CPU 使用率和与 Windows 任务管理器同步

c# - 关于在 MVVM 中适当使用 ViewModelLocator 的问题

javascript - 基于白名单 ID 数组过滤响应对象

c# - 处理条件语句的最佳方法

'map' 语句的 SQL 查询性能

performance - 计算机执行此操作的速度更快 : if (x == 0) or if (! x)