roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

Collection expressions may result in unnecessary tail increment

Open DoctorKrolic opened this issue 1 year ago • 2 comments

Version Used: https://github.com/dotnet/roslyn/commit/b4dc2a111838c3fe1a494bbd3d94d82031e5353b (current sharplab main)

Steps to Reproduce:

using System.Collections.Generic;

public class C
{
    public List<int> M(ICollection<int> c) => [.. c, 4];
}

Expecte codegen for C.M

Expected Behavior: No unnecessary operations

Actual Behavior: Decompiled lowered code looks like this:

public List<int> M(ICollection<int> c)
{
    int num = 1 + c.Count;
    List<int> list = new List<int>(num);
    CollectionsMarshal.SetCount(list, num);
    Span<int> span = CollectionsMarshal.AsSpan(list);
    int num2 = 0;
    IEnumerator<int> enumerator = c.GetEnumerator();
    try
    {
        while (enumerator.MoveNext())
        {
            int current = enumerator.Current;
            span[num2] = current;
            num2++;
        }
    }
    finally
    {
        if (enumerator != null)
        {
            enumerator.Dispose();
        }
    }
    span[num2] = 4;
    num2++; // This increment in unnecessary
    return list;
}

DoctorKrolic avatar Aug 23 '24 12:08 DoctorKrolic

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

ghost avatar Aug 23 '24 12:08 ghost

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

ghost avatar Aug 23 '24 12:08 ghost