EOG*_*EOG 4 c# string validation performance
我想确保 C# 字符串不包含特定字符。
我正在使用string.IndexOfAny(char[])
,在我看来,Regex 在这项任务中会比较慢。有没有更好的方法来实现这一点?速度在我的应用程序中至关重要。
对IndexOf
vs IndexOfAny
vs Regex
vs进行快速基准测试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
笔记:
总体而言,根据干草堆和针的大小,最多regex
会慢indexofany
10 倍。
归档时间: |
|
查看次数: |
1452 次 |
最近记录: |