Collection literals - passing round IReadOnlyList types for perf benefits? #7478
-
A random thought on the way that collection literals will create a new unspeakable type for readonly interfaces If we created a simple function with the purpose of getting us an instance of the new type:
And then I used it whenever creating a collection:
Would I end up with a type with better performance than ImmutableArray under any/some/all conditions? Just interested really |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 13 replies
-
Yes. There are potentially some circumstances where this would be better in some metrics. For example, you might imagine an impl that special cases read-only lists of small sizes, inlining the elements directly into the result. This would be lower in size than an IMmutableArray. That said, IMO, ImmutableArray would likely still be better in other ways. For example, accessing elements happens without the need for interface dispatch with an ImmutableArray. Overall though, the point is that you choose the right type for your case, and we pick the right impl and construction strategy, so you don't have to. Note: IREadOnlyList is also superior if you want the flexibility to change out the impl in the future. But that flexibility comes with the cost of interfaces. So this is ultimately up to you and your needs. |
Beta Was this translation helpful? Give feedback.
-
@mungojam Creating a function allows you to infer the element type, but you can also do the same thing without a method call by writing There's been some interest in a future language feature down the road where you could explicitly infer type arguments, and then you could likely write |
Beta Was this translation helpful? Give feedback.
-
I actually meant these ones which are ImmutableArray specific, though they didn't cover my Select((x,i) => ...) case the other day but it didn't matter https://learn.microsoft.com/en-us/dotnet/api/system.linq.immutablearrayextensions?view=net-7.0 |
Beta Was this translation helpful? Give feedback.
Yes. There are potentially some circumstances where this would be better in some metrics. For example, you might imagine an impl that special cases read-only lists of small sizes, inlining the elements directly into the result. This would be lower in size than an IMmutableArray.
That said, IMO, ImmutableArray would likely still be better in other ways. For example, accessing elements happens without the need for interface dispatch with an ImmutableArray.
Overall though, the point is that you choose the right type for your case, and we pick the right impl and construction strategy, so you don't have to.
Note: IREadOnlyList is also superior if you want the flexibility to change out the impl…