To find out if a string con­tains a piece of sub­string, here are three sim­ple ways of going about it in C#, just to name a few:

Out of curios­ity I wanted to see if there was any notice­able dif­fer­ence in the per­for­mance of each of these options.

Given a sim­ple string “Mary had a lit­tle lamb”, let’s find out how long it takes to test whether or not this string con­tains the terms ‘lit­tle’ (the match case) and ‘big’ (the no match case) using each of these approaches, repeated over 100k times:

image

As you can see, Regex.IsMatch is by far the slow­est option in this test, although using RegexOptions.Compiled yielded slightly faster exe­cu­tion time. What was also inter­est­ing is that String.Contains turned out to be sig­nif­i­cantly faster than String.IndexOf.

If you take a look at the imple­men­ta­tion for String.Contains in a reflec­tor you will see:

image

So that explains the dif­fer­ence between the exe­cu­tion times for String.Contains and String.IndexOf, and indeed if I change the String.IndexOf test to use StringComparison.Ordinal (default is StringComparison.CurrentCulture) then I get an iden­ti­cal result to String.Contains.

With all that said, String.Contains and String.IndexOf is only use­ful for check­ing the exis­tence of an exact sub­string, but Regex is much more pow­er­ful and allows you to do so much more. How­ever, you do end up pay­ing for them even when you don’t need those addi­tional capabilities!

Share

Leave a Reply