What common operations can be made more efficient with Span <T>?
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