Skip to content

List SetCount/AsSpan optimization should produce a list with same capacity as List made with new/Add #72318

@RikkiGibson

Description

@RikkiGibson
List<string> s = ["s"];
Console.WriteLine(s.Capacity);

In absence of CollectionsMarshal.SetCount/AsSpan, the above program outputs 1, but in presence of those methods, it outputs 4.

It feels like the observable behavior of the optimized version should be the same as the non-optimized version, except if we have some really compelling reason to deviate.

Hopefully, we can simply fix by calling the 'List(int capacity)' constructor in the optimized case in addition to the non-optimized case (where we are already doing this.)

Relevant spec bits from https://github.com/dotnet/csharplang/blob/main/proposals/csharp-12.0/collection-expressions.md#known-length-translation:

  • If T supports collection initializers, then:

    • if the type T contains an accessible constructor with a single parameter int capacity, then the literal is translated as:

      T __result = new T(capacity: __len);
      __result.Add(__e1);
      foreach (var __t in __s1)
          __result.Add(__t);
      
      // further additions of the remaining elements

In other words, the default expectation of an optimization for List codegen would be that it behaves the same as the quoted codegen.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions