我想确保 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 不是大海捞针,所有方法的性能都会下降
总体而言,regex
比 indexofany
慢 10 倍,具体取决于干草堆和针的大小。
关于c# - 确保字符串不包含特定字符的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656724/