Set List to Span

less than 1 minute read

.NET 5.0 will add a method to make List <T> Span <T>.

https://github.com/dotnet/runtime/issues/27061

https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.collectionsmarshal.asspan?view=net-5.0

As stated in the issue, it seems that it will be introduced because it is an unsafe function but has a great advantage in terms of performance.

Change List to Span in .NET Core 3

If you can get the array allocated inside List <T>, you can make it Span <T>.

It’s slow to do with reflection, so let’s do it to ʻUnsafe`.

If you treat List <T> as Tuple <T []>, the structure of the class will match, so you can get it.

Note that if you do not secure only list.Count in ʻItem1.AsSpan (0, list.Count), you will end up with a Span with a length of list.Capacity`.

class Program
    static void Main()
    {
        var list = new List<string>
        {
            "Day",
            "Month",
            "fire",
            "water",
            "wood",
            "Money",
            "soil",
        };

        foreach (var item in list.AsSpan()[1..^1])
        {
            Console.WriteLine(item);
        }
//Mon-Fri is displayed
    }
}

public static class Extention
{
    public static Span<T> AsSpan<T>(this List<T> list)
        => System.Runtime.CompilerServices.Unsafe.As<Tuple<T[]>>(list).Item1.AsSpan(0, list.Count);
}

If the structure of List <T> or Tuple <T []> changes, it will not be usable, but by that time Collections Marshal will have been introduced.

Tags:

Updated: