views:

4134

answers:

8

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.

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);
+7  A: 

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

Gonzalo Quero
Sucking up to the boss are we... ? :D You are right though, compared to the time taken to serve a http request, searching through a short string, once, isn't significant.
Fowl
You're evil. I like you :P
Gonzalo Quero
+1  A: 

Answer

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

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.

David Schmitt
+1  A: 

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.

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.

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

Mike Roosa
+2  A: 

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

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.

Brian Rasmussen
Yes, but to use indexof as a bool, he would have to do the comparison outside the function. That would most likely give the same result as Contains, wouldn't it?
Gonzalo Quero
Probably, but you do save one method call (unless it can be inlined). As I said, it will probably never be significant.
Brian Rasmussen
It'll be inlined.
ICR
+21  A: 

Contains calls IndexOf:

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

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

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

IndexOf(string) has no options and Contains() uses an Ordinal compare 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!).

Chris S
+1  A: 

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)

Harry
+5  A: 

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 has exactly the same performance as IndexOf(s2,StringComparison.Ordinal) >= 0 in my tests but it's shorter and makes your intent clear.

ggf31416
@ggf31416: That was an interesting link, thank you. +1
Kb
+1  A: 

Hi,

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)

Getting the total amount of matches for example -

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

Hope this helps!

gary
Hi phild on a separate thread updated this with a version fromhttp://tomasp.net/articles/ahocorasick.aspx which, providing your keywords (needles) don't change is a lot quicker.
gary