Slicing managed arrays using Span<T>

Blue-tilled swimming pool by aalmada

System.String

A string in .NET is nothing more than an immutable array of System.Char (char for short in C#). Immutable means that, once created, its content cannot be modified. You can hold a reference to it and be sure that the string always stays the same. Otherwise, you’d have to clone it. On the down side, it means that many of operations on it require memory allocations and copies.

Benchmarking

Using BenchmarkDotNet and a bit of code, it’s very easy to spot the difference between the use of Substring() and Slice().

  • 16x slower for 10 characters
  • 38x slower for 100 characters
  • 253x slower for 1000 characters

Conclusion

Use Span<char> or ReadOnlySpan<char> for slicing strings. Use them also as argument types so that no conversion back to string is required.

 by the author.

--

--

Principal Engineer @ Farfetch - Innovation Lab https://about.me/antao.almada

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store