I'm looking to convert an array of string to ReadOnlySpan<ReadOnlySpan<Char>>
to optimize a split algorithm.
Is it possible? How?
string[] separators;
ReadOnlyChar<char> totalChars = stackalloc char[separators.Sum(s => s.Length)];
// Copy each string in continu
ReadOnlySpan<ReadOnlySpan<Char>> spanSeparators = stackalloc ReadOnlySpan<ReadOnlySpan<Char>>[separator.Length];
// Slice each string into
No. A span (or a ref-struct more generally) cannot be used as a generic type argument, and since the T
in Span<T>
is a generic type argument: this cannot work.
If the origin here is a string
, you could do something involving Span<ReadOnlyMemory<char>>
, though, using string.AsMemory
(from MemoryExtensions
). However, I wonder if a better approach is to create a custom iterator instead, i.e. don't actually precompute or store anything, and just do the work to find the next item (from the current state) in the MoveNext()
. Since foreach
works via duck-typing, it should work against a ref-struct iterator, allowing you to store a "working" span in a field.