昨天来了一位顾问,不知何故出现了字符串的话题。他提到他注意到对于小于一定长度的字符串,Contains
实际上比 StartsWith
更快。我必须亲眼看到它,所以我写了一个小应用程序,果然,Contains
更快!
这怎么可能?
DateTime start = DateTime.MinValue;
DateTime end = DateTime.MinValue;
string str = "Hello there";
start = DateTime.Now;
for (int i = 0; i < 10000000; i++)
{
str.Contains("H");
}
end = DateTime.Now;
Console.WriteLine("{0}ms using Contains", end.Subtract(start).Milliseconds);
start = DateTime.Now;
for (int i = 0; i < 10000000; i++)
{
str.StartsWith("H");
}
end = DateTime.Now;
Console.WriteLine("{0}ms using StartsWith", end.Subtract(start).Milliseconds);
输出:
726ms using Contains
865ms using StartsWith
我也尝试过使用更长的字符串!
最佳答案
尝试使用 StopWatch
来测量速度而不是 DateTime
检查。
Stopwatch vs. using System.DateTime.Now for timing events
我认为关键是以下加粗的重要部分:
包含
:
This method performs an ordinal (case-sensitive and culture-insensitive) comparison.
开始于
:
This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture.
我认为关键是序数比较,它相当于:
An ordinal sort compares strings based on the numeric value of each Char object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important in your application, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase using the invariant culture and then performing an ordinal comparison on the result.
引用资料:
http://msdn.microsoft.com/en-us/library/system.string.aspx
http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx
http://msdn.microsoft.com/en-us/library/baketfxw.aspx
使用 Reflector 你可以看到两者的代码:
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
public bool StartsWith(string value, bool ignoreCase, CultureInfo culture)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (this == value)
{
return true;
}
CultureInfo info = (culture == null) ? CultureInfo.CurrentCulture : culture;
return info.CompareInfo.IsPrefix(this, value,
ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
关于c# - 包含比 StartsWith 快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3120056/