c# - 包含比 StartsWith 快?

标签 c# .net performance string

昨天来了一位顾问,不知何故出现了字符串的话题。他提到他注意到对于小于一定长度的字符串,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/

相关文章:

c# - 使用后台 worker 高效写入 GUI 线程

c# - Rhino Mocks 约束和字典参数

c# - 在 c# rabbitmq 客户端中得到 "Pipelining of requests forbidden"

c# - 基于 MySQL 表创建 C# 类

python - 在 Python 中测量性能

performance - 为什么嵌套的 MaybeT 会导致指数分配

c# - 将 Web API 用于 Windows 服务以通过轮询接收命令和执行任务?

c# - 删除选中的父节点和子节点——集合被修改;枚举操作可能无法执行

java - 高效的Android设计和类的使用

c# - HttpWebResponse 的编码问题