Using Span<T> as a replacement for Substring
Asked Answered
S

1

10

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();
Spearwort answered 1/1, 2019 at 18:28 Comment(2)
Yes; creating a String negates the benefit by allocating a string. You need to return a Span<T>Puggree
My ultimate use of this is to store it in a database via EF, which is string type, I guess then I won't see the benefit for this particular use case?Spearwort
G
5

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.

Gschu answered 1/1, 2019 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.