Alex Rivera | Logout

How does String.Contains work?

Asked 2010-09-22T13:08:45.787
9

Possible Duplicate:
What algorithm .Net use for searching a pattern in a string?

I have a loop in my program that gets a line from a file. Then there is a check to whether the line contains a string

if(line.Contains("String"))
{
    //Do other stuff
}

There are over 2 million rows in the file so if I can quicken the speed by even 1/10th millisecond then this would save me over 3 minutes on each run.

So... Say a line is 1000 chars long, is it quicker to look for a short or long string, or does it not make a difference?

line.Contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

or

line.Contains("ABCDEFG")

Thank you in advance.

Edit
Report

1 Answer

3

If .NET String.Contains uses the Boyer-Moore algorithm it is faster to search a longer string.

May I suggest that if you are reading a delimited file so for example each line is a series of text fields separated by commas that you could save some searching time by not searching from position 0 in the line if you know it can't be before character 40 for example.

It is quite common to split a line using the String Spilt function on a delimiter character this returns an array of Strings. Then you would search only within the field where the value could appear. This will be quicker too.

answered 2010-09-22T13:16:59.390

Your Answer