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:
- String.Contains
- String.IndexOf where the return value is >= 0
- Regex.IsMatch
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:
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:
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 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.
Interesting.
Thanks
Here’s a blog which benchmarks several different C# techniques. Makes for a great read, especially for those who are looking for the *fastest* way:
http://blogs.davelozinski.com/curiousconsultant/csharp-net-fastest-way-to-check-if-a-string-occurs-within-a-string
_
Pingback: hashmap lookup vs string.contains performance in c# | DiscVentionsTech
As a Newbie, I am continuously searching online for articles that can aid me. Thank you affdffdgdfkdadke