Add more extensibility points for collection expression optimizations #9697
Replies: 3 comments 4 replies
-
|
I support expanding the types allowed by the CreateBuilder Create method, e.g. to This would not allow the compiler to de-hardcode the optimization for ImmutableArray because it is not safe for ImmutableArray to have an API that constructs an immutable array around a |
Beta Was this translation helpful? Give feedback.
-
|
I'm amenable to this. It would be nice to not have to special case certain apis with the CollectionMarshal bypass. The lang/compiler could certainly look for certain api patterns (or attributes) telling it which apis are safe to pass an array of values into. That said, the reason we didn't do this originally was simply that when we explored the ecosystem, we did not find enough cases where this would be useful. In other words, the number of collections that backed by their own owned copy of an array was marginal. I get that the request here is purposefully vague. But are there existing APIs you own that would actually benefit here? If so, can you link to them? We'd need real motivation from API authors stating that this is an actual impediment to them (with examples) to help motivate this. We would be unlikely to do it based on speculative need for apis that don't actually come to fruition. |
Beta Was this translation helpful? Give feedback.
-
|
I find this problem interesting, and, re: the record custom equality problem, I wonder if the scales have fully tipped at this point, toward using a wrapper type to customize equality per-property, rather than source generator stuff. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Motivation: immutable collection types suffer from redundant temporary copies when collection expressions are used. Visual Studio has inline hints recommending this syntax everywhere, leading users into sub-optimal code whenever such collections are used.
Consider:
Here C# will lower
[.. arr]toMyCollection.Create(arr.ToArray()). So we have two allocations:arr.ToArray()MyCollection.Create- since it takes aReadOnlySpan, it has to copy the collection to its internal array.The C# compiler works around this for a set of hardcoded "well-known" types and members with optimizations like:
In this scenario, what if we could define a
T[]overload ofCreatethat the C# compiler would use? Then we could decide if we'll re-use that array internally and avoid a copy. For instance:This could not only provide library authors with the same optimizations as "well-known" library types, but allow de-hardcoding these things in the C# compiler.
This is but a suggestion of how to fix this; any other extensibility beyond a method taking
ReadOnlySpanwould help.Beta Was this translation helpful? Give feedback.
All reactions