是String.Contains()比String.IndexOf快()? [英] Is String.Contains() faster than String.IndexOf()?

查看:777
本文介绍了是String.Contains()比String.IndexOf快()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有谁知道,如果 String.Contains方法性能更好比 String.IndexOf方法

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

    // 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);

有趣的事实

推荐答案

包含电话的IndexOf

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

这就要求 CompareInfo.IndexOf ,最终使用CLR实现。

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

。 CPP>这将显示您(寻找的 CaseInsensitiveCompHelper 的)。

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

的IndexOf(字符串)没有选项,包含()使用序号比较(一个字节逐字节的比较,而不是试图进行智能对比,例如,电子与E)。

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 将稍快(理论上)为的IndexOf 去直接一个字符串搜索使用FindNLSString从KERNEL32.DLL(反射的力量!)。

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

这篇关于是String.Contains()比String.IndexOf快()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆