dotnet/roslyn

Slice can be simplified does not produce the same code

Aperta

#47.629 aperta il 11 set 2020

 (10 commenti) (5 reazioni) (0 assegnatari)C# (4257 fork)batch import
Area-CompilersCode Gen QualityFeature - Rangehelp wanted

Metriche repository

Star
 (20.414 stelle)
Metriche merge PR
 (Merge medio 6g 17h) (256 PR mergiate in 30 g)

Descrizione

Currently the IDE suggest with Span not to use slice but instead use the Range indexer (IDE0057: Slice can be simplified to this). So the original code:

new Vector<T>(B.Slice(Idx))

is then translated to

new Vector<T>(B[Idx..])

the resulting generated code is different (which is OK)

    public void WithSlice() {
        ReadOnlySpan<float> A = new float[100];
        
        for (int i=0; i<A.Length; i+= Vector<float>.Count)
            new Vector<float>(A.Slice(i));   
    }
    
       public void WithRange() {
        ReadOnlySpan<float> A = new float[100];
        
        for (int i=0; i<A.Length; i+= Vector<float>.Count)
            new Vector<float>(A[i..]);
    }

and the result taken from sharplab:

    public void WithSlice()
    {
        ReadOnlySpan<float> readOnlySpan = new float[100];
        for (int i = 0; i < readOnlySpan.Length; i += Vector<float>.Count)
        {
            new Vector<float>(readOnlySpan.Slice(i));
        }
    }

    public void WithRange()
    {
        ReadOnlySpan<float> readOnlySpan = new float[100];
        for (int i = 0; i < readOnlySpan.Length; i += Vector<float>.Count)
        {
            ReadOnlySpan<float> readOnlySpan2 = readOnlySpan;
            int length = readOnlySpan2.Length;
            int num = i;
            int length2 = length - num;
            new Vector<float>(readOnlySpan2.Slice(num, length2));
        }
    }

but the JIT Asm seems to be different. I didn't make any performance comparisons, but for my environment it is crucial that the suggested rewrite does not alter the performance of the code.

Guida contributor