An alternative method for obtaining a substring is through slicing, as demonstrated in the following example:
ReadOnlySpan<char> slice = this.LongTestString[1..25];
Alternatively, you can achieve the same result using the AsSpan()
method, as illustrated below:
var slice = this.LongTestString.AsSpan()[1..25];
Benchmark Results
Benchmark tests show that employing the AsSpan()
method yields a 2.07x performance boost and consumes fewer memory resources.
This is how I have it configured in my EditorConfig to check for this issue: dotnet_diagnostic.CA1831.severity = error
Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf 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.
One thought on “String Performance: Optimizing String Substring Extraction – Slicing vs. AsSpan()”