为什么函数isprefix比C#中的Startswith更快? [英] Why is function isprefix faster than Startswith in C#?
问题描述
有人知道为什么C#(.NET)的 StartsWith 函数比 IsPrefix ?
Does anyone know why C# (.NET)'s StartsWith function is considerably slower than IsPrefix?
推荐答案
我认为这主要是在获取线程的当前文化.
I think it's mostly fetching the thread's current culture.
如果您将Marc的测试更改为使用String.StartsWith
的这种形式:
If you change Marc's test to use this form of String.StartsWith
:
Stopwatch watch = Stopwatch.StartNew();
CultureInfo cc = CultureInfo.CurrentCulture;
for (int i = 0; i < LOOP; i++)
{
if (s1.StartsWith(s2, false, cc)) chk++;
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds + "ms; chk: " + chk);
距离更近了.
如果使用s1.StartsWith(s2, StringComparison.Ordinal)
,它比使用CompareInfo.IsPrefix
快得多(当然取决于CompareInfo
).在我的盒子上,结果是(不是科学地):
If you use s1.StartsWith(s2, StringComparison.Ordinal)
it's a lot faster than using CompareInfo.IsPrefix
(depending on the CompareInfo
of course). On my box the results are (not scientifically):
- s1.StartsWith(s2):6914ms
- s1.StartsWith(s2,false,culture):5568ms
- compare.IsPrefix(s1,s2):5200ms
- s1.StartsWith(s2,StringComparison.Ordinal):1393毫秒
显然是因为它实际上只是比较每个点的16位整数,这非常便宜.如果您不想想要进行文化敏感的检查,那么和的性能对您尤为重要,那就是我要使用的重载.
Obviously that's because it's really just comparing 16 bit integers at each point, which is pretty cheap. If you don't want culture-sensitive checking, and performance is particularly important to you, that's the overload I'd use.
这篇关于为什么函数isprefix比C#中的Startswith更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!