-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
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
Tsupports collection initializers, then:
if the type
Tcontains an accessible constructor with a single parameterint 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.