I have read a few articles about how Span can be used to replace certain string operations. As such I have updated some code in my code base to use this new feature, however, to be able to use it in-place I then have to call .ToString()
.
Does the .ToString()
effectively negate the benefit I get from using Span<T>
rather than Substring
as this would have to allocate memory? In which case how do I reap the benefits if Span in this way, or is it just not possible?
//return geofenceNamesString.Substring(0, 50); Previous code
return geofenceNamesString.AsSpan().Slice(0, 50).ToString();
There is no benefit in your case.
A span is useful if you keep multiple "references" into the same array of data. For example if you read a file into RAM and then kept references to each line, so you don't have to copy each line, but only to keep its position in the big string.
You are making a copy of your string one way or another. So just go with the easier, more readable way of Substring
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With