-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[API Proposal]: Add CollectionsMarshal.AsMemory(List<T>)
#90141
Comments
Tagging subscribers to this area: @dotnet/area-system-memory Issue DetailsBackground and motivationThe existing API Proposal namespace System.Runtime.InteropServices;
public static class CollectionsMarshal
{
// Existing method:
public static Span<T> AsSpan<T>(List<T>? list)
// New method:
+ public static Memory<T> AsMemory<T>(List<T>? list)
} API Usageasync Task FooAsync(TextWriter writer)
{
var list = new List<char>();
// ...fill the collection
await writer.WriteAsync(CollectionsMarshal.AsMemory(list));
} Alternative DesignsNo response RisksNo response
|
The |
See also #87210. |
Could this not be revisited? It's been 4 years since that API review. |
While |
Why would it have to bake in the notion of it being a |
I understand that it's possible to get the underlying array from a |
Because |
But that would be an implementation detail. The API would still return an abstraction. |
Let's say |
I mean I wouldn't have the expectation that it has to be 100% allocation free. I would expect that the data wouldn't be copied so that I could use this with huge data sets, but a small allocation just for the memory manager seems fine IMO. |
It's a key expectation in general for this kind of method, that it's effectively a cheap, allocation-free cast. |
The use case presented in the OP seems like it would be better served by an |
I guess we have different expectations. Whenever I'm using |
Background and motivation
The existing
CollectionsMarshal.AsSpan
method is really useful in order to be able to get a span from aList<T>
, however, in many scenarios, e.g. when calling async methods, what you really need is aMemory<T>
instead. Since you can't get aMemory<T>
from aSpan<T>
, you currently need to make a copy of the data. This could be avoided if there was an ability to get aMemory<T>
directly from aList<T>
.API Proposal
namespace System.Runtime.InteropServices; public static class CollectionsMarshal { // Existing method: public static Span<T> AsSpan<T>(List<T>? list) // New method: + public static Memory<T> AsMemory<T>(List<T>? list) }
and if #90138 is approved, then also:
namespace System.Runtime.InteropServices; public static class ImmutableCollectionsMarshal { // Method proposed in #90138: public static Span<T> AsSpan<T>(ImmutableArray<T>.Builder? builder); // New method: + public static Span<T> AsMemory<T>(ImmutableArray<T>.Builder? builder); }
API Usage
Alternative Designs
No response
Risks
No response
The text was updated successfully, but these errors were encountered: