Skip to content

JIT doesn't elide bounds checking when iterating over a span and an array of known length #110986

@itsBuggingMe

Description

@itsBuggingMe

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;
}

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIin-prThere is an active PR which will close this issue when it is mergedtenet-performancePerformance related issue

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions