Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Span<T> as a replacement for Substring

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();
like image 469
Chris Avatar asked Jan 01 '19 18:01

Chris


1 Answers

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.

like image 188
nvoigt Avatar answered Oct 02 '22 22:10

nvoigt