Specify the initial size forToList
or ToArray
#118820
Replies: 1 comment 1 reply
-
This has been previously discussed and rejected, see e.g. #83807 and #29620. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Rationale
For performance-related reasons, folks can specify the initial size of a
List<T>
when creating one via the ctor:To specify the initial size of the underlying array to avoid resizing, which makes it a nice low-hanging fruit in performance-related scenarios where the rough size is known upfront.
Unfortunately, this doesn't work well with LINQ. There is no way of specifying the initial size like:
foo.Where(...).ToList(size: 1_000);
. Now, one can make the argument usingfor(each)
loop and creating the list upfront would be the more sensible choice here. Sure, but that only helps so far.When using Entity Framework often times I know exactly how many elements I get (or at most how many items). If the dataset returned is not only 100 elements, EF will (maybe?) have to resort to a lot of resizing internally if
ToList(Async)
is used.While there are some workarounds (like
AsAsyncEnumerable
): They are not always the right tool and are error-prone.Therefore: Is there any compelling reason against extending the API to allow an initial size?
Beta Was this translation helpful? Give feedback.
All reactions