What common operations can be made more efficient with Span <T>?

Let's say I have a web application, and I want to use a new type Span<T>to reduce pressure in the GC and increase productivity.

What patterns should I look for? Are there any typical operations that the .NET team had in mind when implementing this new feature?

+4
source share
1 answer

There are quite a few cases where this new class and infrastructure can help, but if they are shared, it depends on your code ...

See this pre-C # 7.2 for an example:

static void Main(string[] args)
{
    byte[] file = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] header = file.Take(4).ToArray();
    byte[] content = file.Skip(4).ToArray();

    bool isValid = IsValidHeader(header);
}

private static bool IsValidHeader(byte[] header)
{
    return header[0] == 0 && header[1] == 1;
}

file.Take(4).ToArray() byte[] content = file.Skip(4).ToArray(); : , . , ( 10 file, 20 ).

# 7.2:

static void Main(string[] args)
{
    byte[] file = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
    var header = file.Take(4);
    var content = file.Skip(4);

    bool isValid = IsValidHeader(header);
}

private static bool IsValidHeader(ReadOnlySpan<byte> header)
{
    return header[0] == 0 && header[1] == 1;
}

ReadOnlySpan<T> ( Span<T>) ! 10 . . , Span<T>, .

, IEnumerable<T>, ( , , content).

+3

Source: https://habr.com/ru/post/1689380/


All Articles