Pattern: Use of range-based indexer for ReadOnlySpan
/ReadOnlyMemory
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 ReadOnlySpan<T>
or ReadOnlyMemory<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)
{
ReadOnlySpan<byte> tmp1 = arr[0..2];
ReadOnlyMemory<byte> tmp3 = arr[5..8];
}
Example of correct code:
public void TestMethod(byte[] arr)
{
ReadOnlySpan<byte> tmp1 = arr.AsSpan()[0..2];
ReadOnlyMemory<byte> tmp3 = arr.AsMemory()[5..8];
}