Skip to content

API for inserting a Span<T> into a List<T> efficiently #1530

@josetr

Description

@josetr

EDITED 9/22/2022 by @stephentoub:

namespace System.Collections.Generic
{
    public class List<T>
    {
+        public void AddSpan(ReadOnlySpan<T> span);
+        public void InsertSpan(int index, ReadOnlySpan<T> span);

+        public void CopyTo(Span<T> span);
    }
}
  • We can't just add an AddRange overload as it's ambiguous for anything convertible to both span and enumerable, like array. We could alternatively call it AddRange and add overloads as well for arrays and strings.

Perhaps an AddRange overload taking a Span<T> can be added to the List class?

var list = new List<byte>();
list.AddRange(new Span<byte>());

Workarounds

foreach(var b in span)
    list.Add(b); // Inefficient only copying one byte at a time
var list = new List<byte>();
var span = new Span<byte>();
list.AddRange(span.ToArray()); Silly allocation

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions