-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Closed
Labels
Area-CompilersCode Gen QualityRoom for improvement in the quality of the compiler's generated codeRoom for improvement in the quality of the compiler's generated codeFeature - Collection Expressions
Milestone
Description
Version Used:
Version 17.9.0 Preview 1.0 [34231.268.main]
Steps to Reproduce:
static int[] GetArray(List<int> list) => list.ToArray(); IDE0305 recommends rewriting this to:
static int[] GetArray(List<int> list) => [.. list];which would be fine if that still compiled down to a list.ToArray() call, but instead it compiles down to the equivalent of:
int[] array = new int[list.Count];
int num = 0;
foreach (int item in list)
{
array[num] = item;
num++;
}which is significantly less efficient, especially for longer lists where the entire copy would instead be done as a vectorized memcpy invocation.
It's also worse if the list was actually empty: List<T>.ToArray() will return an empty array singleton if the count is 0, but the above code will end up always allocating a new empty array 😦
cc: @cston, @CyrusNajmabadi
Mertsch, PaulusParssinen, JustSergey, LorandBiro and pawchen
Metadata
Metadata
Assignees
Labels
Area-CompilersCode Gen QualityRoom for improvement in the quality of the compiler's generated codeRoom for improvement in the quality of the compiler's generated codeFeature - Collection Expressions