C# String.Contains() 比 String.IndexOf() 快吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/498686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:44:32  来源:igfitidea点击:

Is String.Contains() faster than String.IndexOf()?

c#.netasp.netperformancestring

提问by Kb.

I have a string buffer of about 2000 characters and need to check the buffer if it contains a specific string.
Will do the check in a ASP.NET 2.0 webapp for every webrequest.

我有一个大约 2000 个字符的字符串缓冲区,需要检查缓冲区是否包含特定字符串。
将为每个 Web 请求检查 ASP.NET 2.0 Web 应用程序。

Does anyone know if the String.Contains methodperforms better than String.IndexOf method?

有谁知道String.Contains 方法是否比String.IndexOf 方法性能更好?

    // 2000 characters in s1, search token in s2
    string s1 = "Many characters. The quick brown fox jumps over the lazy dog"; 
    string s2 = "fox";
    bool b;
    b = s1.Contains(s2);
    int i;
    i = s1.IndexOf(s2);

Fun fact

有趣的事实

采纳答案by Chris S

Containscalls IndexOf:

Contains电话IndexOf

public bool Contains(string value)
{
    return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

Which calls CompareInfo.IndexOf, which ultimately uses a CLR implementation.

其中调用CompareInfo.IndexOf,最终使用 CLR 实现。

If you want to see how strings are compared in the CLR this will show you(look for CaseInsensitiveCompHelper).

如果您想查看 CLR 中字符串的比较方式,这将显示给您(查找CaseInsensitiveCompHelper)。

IndexOf(string)has no options and Contains()uses an Ordinal compare (a byte-by-byte comparison rather than trying to perform a smart compare, for example, e with é).

IndexOf(string)没有选项并Contains()使用序数比较(逐字节比较,而不是尝试执行智能比较,例如,e 与 é)。

So IndexOfwill be marginally faster (in theory) as IndexOfgoes straight to a string search using FindNLSString from kernel32.dll (the power of reflector!).

所以IndexOf会稍微快一点(理论上),因为IndexOf直接使用来自 kernel32.dll 的 FindNLSString 进行字符串搜索(反射器的力量!)。

Updated for .NET 4.0- IndexOf no longer uses Ordinal Comparison and so Contains can be faster. See comment below.

针对 .NET 4.0 更新- IndexOf 不再使用顺序比较,因此包含可以更快。请参阅下面的评论。

回答by Gonzalo Quero

Probably, it will not matter at all. Read this post on Coding Horror ;): http://www.codinghorror.com/blog/archives/001218.html

也许,这根本无关紧要。阅读有关 Coding Horror 的这篇文章;):http: //www.codinghorror.com/blog/archives/001218.html

回答by David Schmitt

Use a benchmark library, like this recent foray from Jon Skeetto measure it.

使用基准库,例如Jon Skeet 最近的尝试来衡量它。

Caveat Emptor

买者自负

As all (micro-)performance questions, this depends on the versions of software you are using, the details of the data inspected and the code surrounding the call.

与所有(微观)性能问题一样,这取决于您使用的软件版本、所检查数据的详细信息以及调用周围的代码。

As all (micro-)performance questions, the first step has to be to get a running version which is easily maintainable. Then benchmarking, profiling and tuning can be applied to the measured bottlenecks instead of guessing.

与所有(微)性能问题一样,第一步必须是获得一个易于维护的运行版本。然后可以将基准测试、分析和调整应用于测量的瓶颈而不是猜测。

回答by Mike Roosa

From a little reading, it appears that under the hood the String.Contains method simply calls String.IndexOf. The difference is String.Contains returns a boolean while String.IndexOf returns an integer with (-1) representing that the substring was not found.

从一点点阅读来看,似乎在底层,String.Contains 方法只是调用 String.IndexOf。不同之处在于 String.Contains 返回一个布尔值,而 String.IndexOf 返回一个整数,其中 (-1) 表示未找到子字符串。

I would suggest writing a little test with 100,000 or so iterations and see for yourself. If I were to guess, I'd say that IndexOf may be slightly faster but like I said it just a guess.

我建议用 100,000 次左右的迭代编写一个小测试,然后自己看看。如果我猜的话,我会说 IndexOf 可能会稍微快一点,但就像我说的那样只是一个猜测。

Jeff Atwood has a good article on strings at his blog. It's more about concatenation but may be helpful nonetheless.

Jeff Atwood 在他的博客上有一篇关于弦乐的好文章。它更多是关于串联,但可能会有所帮助。

回答by Brian Rasmussen

By using Reflector, you can see, that Contains is implemented using IndexOf. Here's the implementation.

通过使用 Reflector,您可以看到,Contains 是使用 IndexOf 实现的。这是实现。

public bool Contains(string value)
{
   return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

So Contains is likely a wee bit slower than calling IndexOf directly, but I doubt that it will have any significance for the actual performance.

所以包含可能比直接调用 IndexOf 慢一点,但我怀疑它对实际性能是否有任何意义。

回答by Andrew Harry

If you really want to micro optimise your code your best approach is always benchmarking.

如果你真的想微优化你的代码,你最好的方法总是基准测试。

The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch

.net 框架有一个优秀的秒表实现 - System.Diagnostics.Stopwatch

回答by ggf31416

Contains(s2) is many times (in my computer 10 times) faster than IndexOf(s2) because Contains uses StringComparison.Ordinal that is faster than the culture sensitive search that IndexOf does by default (but that may change in .net 4.0 http://davesbox.com/archive/2008/11/12/breaking-changes-to-the-string-class.aspx).

contains(s2) 比 IndexOf(s2) 快很多倍(在我的计算机中 10 倍),因为 Contains 使用 StringComparison.Ordinal 比 IndexOf 默认执行的区域性敏感搜索更快(但在 .net 4.0 http中可能会改变: //davesbox.com/archive/2008/11/12/break-changes-to-the-string-class.aspx)。

Contains has exactly the same performance as IndexOf(s2,StringComparison.Ordinal) >= 0 in my tests but it's shorter and makes your intent clear.

在我的测试中,包含与 IndexOf(s2,StringComparison.Ordinal) >= 0 具有完全相同的性能,但它更短并且使您的意图清晰。

回答by gary

Just as an update to this I've been doing some testing and providing your input string is fairly large then parallel Regex is the fastest C# method I've found (providing you have more than one core I imagine)

作为对此的更新,我一直在做一些测试并提供您的输入字符串相当大然后并行正则表达式是我发现的最快的 C# 方法(假设您有多个我想象的核心)

Getting the total amount of matches for example -

例如获取匹配的总数 -

needles.AsParallel ( ).Sum ( l => Regex.IsMatch ( haystack , Regex.Escape ( l ) ) ? 1 : 0 );

Hope this helps!

希望这可以帮助!

回答by magallanes

I am running a real case (in opposite to a synthetic benchmark)

我正在运行一个真实案例(与合成基准相反)

 if("=,<=,=>,<>,<,>,!=,==,".IndexOf(tmps)>=0) {

versus

相对

 if("=,<=,=>,<>,<,>,!=,==,".Contains(tmps)) {

It is a vital part of my system and it is executed 131,953 times (thanks DotTrace).

它是我系统的重要组成部分,执行了 131,953 次(感谢 DotTrace)。

However shocking surprise, the result is the opposite that expected

然而令人震惊的惊喜,结果却与预期相反

  • IndexOf 533ms.
  • Contains 266ms.
  • IndexOf 533ms。
  • 包含 266 毫秒。

:-/

:-/

net framework 4.0 (updated as for 13-02-2012)

net framework 4.0(更新至 13-02-2012)

回答by Zargontapel

For anyone still reading this, indexOf() will probably perform better on most enterprise systems, as contains() is not compatible with IE!

对于仍在阅读本文的任何人, indexOf() 可能会在大多数企业系统上表现更好,因为 contains() 与 IE 不兼容!