Performance Test – String.Contains vs String.IndexOf vs Regex.IsMatch

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­i­ty I want­ed to see if there was any notice­able dif­fer­ence in the per­for­mance of each of these options.

Giv­en 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 approach­es, repeat­ed over 100k times:

image

As you can see, Regex.IsMatch is by far the slow­est option in this test, although using RegexOptions.Compiled yield­ed slight­ly faster exe­cu­tion time. What was also inter­est­ing is that String.Contains turned out to be sig­nif­i­cant­ly 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­ev­er, you do end up pay­ing for them even when you don’t need those addi­tion­al capa­bil­i­ties!