Pattern: Use of range-based indexer for Span
/Memory
Issue: -
The range indexer on a Span<T>
is a non-copying Slice
operation. But for the range indexer on an array, the method GetSubArray
will be used instead of Slice
, which produces a copy of the requested portion of the array. This copy is usually unnecessary when it's implicitly used as a Span<T>
or Memory<T>
value.
If a copy isn't intended, use the AsSpan
or AsMemory
method to avoid the unnecessary copy. If the copy is intended, either assign it to a local variable first or add an explicit cast. The analyzer only reports when an implicit cast is used on the result of the range indexer operation.
Example of incorrect code:
public void TestMethod(byte[] arr)
{
Span<byte> tmp2 = arr[0..5];
Memory<byte> tmp4 = arr[5..10];
}
Example of correct code:
public void TestMethod(byte[] arr)
{
Span<byte> tmp2 = arr.AsSpan()[0..5];
Memory<byte> tmp4 = arr.AsMemory()[5..10];
}