Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring implementation via Span<T>

How would an implementation of a SubstringFromStart method look like when Span<T> should be leveraged? Assuming substringLength <= input.Length:

 ReadOnlySpan<char> span = input.AsSpan().Slice(0, substringLength);
 return new string(span.ToArray());

Is this the way to go? Is there a better, more concise way than new string(span.ToArray())?

like image 408
David Avatar asked Feb 06 '18 13:02

David


1 Answers

Is this the way to go?

No, using Span<T> is useless here, since you need a character array for the string constructor (there is none that accepts a Span<char> yet).

You would benefit using Span<T> here if:

  • You would return the Span<char>, rather than a string. Then you wouldn't need the string allocation;
  • You receive a Span<char> as input and you never need to materialize it to an array, or you wouldn't need a intermediate materialization (when passing it into the method for example).
like image 80
Patrick Hofman Avatar answered Nov 13 '22 17:11

Patrick Hofman