[Proposal] Allow take underlying array from a List<T> #58284
-
MotivationTo extract the data from a public int[] ComputeSomething(int max)
{
var list = new List<int>();
for(var i = 0; i < max; i++) {
list.Add(i * max);
}
// list is not being used anymore
return list.ToArray();
} ProposalWould be great to allow us to just take the inner array of the public Span<int> ComputeSomething(int max)
{
var list = new List<int>();
for(var i = 0; i < max; i++) {
list.Add(i * max);
}
// list is not being used anymore, lets just take the data
return list.TakeArray();
} API Designpublic class List<T> // ...
{
internal T[] _items;
internal int _size;
// ...
public Span<T> TakeArray()
{
var array = _items;
var size = _size;
// Reset this List<T>
_size = 0;
_items = Array.Empty<T>();
// Returns the data
return new Span<T>(array, 0, size);
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 0 comments 7 replies
-
This would be a request for the runtime repository, they deal with the APIs of the base class library. |
Beta Was this translation helpful? Give feedback.
-
Having There's no way to enforce that the reference to the Plus, in the vast majority of cases, My personal experience is that use of |
Beta Was this translation helpful? Give feedback.
-
How are you going to handle the array (almost) never being the exact size for all the items? The underlying storage of a Resizing the array would involve allocation and copying, so you're stuck between a rock and a hard place. (This is what I don't think you can rely on setting Also, if you know the Capacity you need in advance, you can directly allocate an array anyway. Last observation: do you have benchmarks to show that the reduction in allocations is worth it? Or are you working on intuition? My experience with measured performance optimisation, well, I've already stated that. |
Beta Was this translation helpful? Give feedback.
This would be a request for the runtime repository, they deal with the APIs of the base class library.