5

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())?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
David
  • 2,426
  • 3
  • 24
  • 36

1 Answers1

5

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).
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325