I have a List<T>
containing some data. I would like to pass it to a function which accepts ReadOnlySpan<T>
.
List<T> items = GetListOfItems();
// ...
void Consume<T>(ReadOnlySpan<T> buffer)
// ...
Consume(items??);
In this particular instance T is byte
but it doesn't really matter.
I know I can use .ToArray()
on the List, and the construct a span, e.g.
Consume(new ReadOnlySpan<T>(items.ToArray()));
However this creates a (seemingly) unneccessary copy of the items. Is there any way to get a Span directly from a List? List<T>
is implemented in terms of T[]
behind the scenes, so in theory it's possible, but not as far as I can see in practice?
List<T>
, in natural ways. Otherwise you can use reflection to access backing array and callAsSpan
on it. – CulbersonSpan<T>
for performance reasons, perhaps you shouldn't be starting with aList<T>
in the first place? – ThickkneeAdd
operation which means theSpan
will end up pointing to a dangling array and stale data. Imagine adding 2 items to an empty list, taking a span, then adding another item, causing a reallocation and then modifying all stored items. The span will end up looking at a stale copy of the data – AnthropophagiteReadOnlySpan
holds a dangled array reference. 2) The internal array gets a size that will be doubled whenever it needs to be increased, so it might contain default values for that type which aren't contained in the list(array.Length > list.Count
). If you are going to truncate that part you have to create a new array anyway. – ArdaList<T>
is fast. Just because it abstracts away the need to manually recreate the underlying array at a larger size yourself doesn't automatically make it slow. It's still just an array underneath. – Postnasal