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

Yan Cui

I help clients go faster for less using serverless technologies.

To find out if a string contains a piece of substring, here are three simple ways of going about it in C#, just to name a few:

Out of curiosity I wanted to see if there was any noticeable difference in the performance of each of these options.

Given a simple string “Mary had a little lamb”, let’s find out how long it takes to test whether or not this string contains the terms ‘little’ (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 slowest option in this test, although using RegexOptions.Compiled yielded slightly faster execution time. What was also interesting is that String.Contains turned out to be significantly faster than String.IndexOf.

If you take a look at the implementation for String.Contains in a reflector you will see:

image

So that explains the difference between the execution 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 identical result to String.Contains.

With all that said, String.Contains and String.IndexOf is only useful for checking the existence of an exact substring, but Regex is much more powerful and allows you to do so much more. However, you do end up paying for them even when you don’t need those additional capabilities!


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


4 thoughts on “Performance Test – String.Contains vs String.IndexOf vs Regex.IsMatch”

  1. Pingback: hashmap lookup vs string.contains performance in c# | DiscVentionsTech

Leave a Comment

Your email address will not be published. Required fields are marked *