Skip to content

Fast Arrays and Lists

Spans of arrays are faster than using array variables directly:

var arr = new[] { 1, 2, 3}; // Slow

Span<int> arr = new[] { 1, 2, 3}; // Fast

However, for Lists this doesn't work. Instead use the CollectionsMarshall.AsSpan() approach:

List<int> list = new List<int> { 1, 3, 3};

var span.CollectionsMarshall.AsSpan(list)

for (var i = 0; i < span.Length(), i++>)
{
    var value = span[i];
    ...
}

Beware though that this can fail and not throw an error for mutating lists.