Description
If you ensure that the length of an array and a span are the same, the JIT will still emit bounds checking on only the span when indexing.
This does not occur when iterating over a span and a span, or an array and an array.
public static int SumSpanArray(int[] arr, Span<int> span)
{
int counter = 0;
if(arr.Length != span.Length)
return 0;
//bounds check here
for(int i = 0; i < arr.Length; i++)
counter += arr[i] + span[i];
return counter;
}
Sharplab example here
Regression?
I have only used Sharplab to test this, but it doesn't seem likely to be a regression.
Analysis
I don't know why, but curiously enough when checking the span length when iterating over a span + array, there is no bound check
public static int SumSpanArray2(int[] arr, Span<int> span)
{
int counter = 0;
if(arr.Length != span.Length)
return 0;
//no bound check
for(int i = 0; i < span.Length; i++)
counter += arr[i] + span[i];
return counter;
}
Description
If you ensure that the length of an array and a span are the same, the JIT will still emit bounds checking on only the span when indexing.
This does not occur when iterating over a span and a span, or an array and an array.
Sharplab example here
Regression?
I have only used Sharplab to test this, but it doesn't seem likely to be a regression.
Analysis
I don't know why, but curiously enough when checking the span length when iterating over a span + array, there is no bound check