String Performance: Checking for a Substring

Updated February 2024

There are three primary methods to examine the presence of a string within another string. These methods, derived from the string type, are:

  • StartsWith()
  • EndsWith()
  • Contains()

Here is an example illustrating the usage of Contains().

bool result = "David McCarter".Contains("David");

Benchmark Results

When employing StartsWith(), utilizing it with StringComparison.Ordinal and StringComparison.OrdinalIgnoreCase yields nearly identical speeds. Additionally, employing Ordinal is 42.38 times more efficient than using it without specifying a StringComparison.

As evident in the performance analysis of EndsWith(), employing it with StringComparison.OrdinalIgnoreCase is 1.47 times faster than using StringComparison.Ordinal, and a notable 7.68 times faster compared to not specifying a StringComparison.

When utilizing Contains(), opting for no StringComparison specification proves to be the most performant, being 1.39 times faster than using StringComparison.Ordinal and 1.82 times faster than using StringComparison.OrdinalIgnoreCase.

For further information on checking for a substring, please consult the Internationalization and Localization chapter in my code performance book.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

2 thoughts on “String Performance: Checking for a Substring

  1. The performance of Contains should vary significantly with the position of the substring within the master string. Using your example above, it should be very near in time to StartsWith and slightly faster (by clock cycles/nS) than EnddWith…

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.