You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In basically every project I use ImmutableArray in, I end up creating an extension for ToImmutableAndClear on the builder type, which takes advantage of MoveToImmutable() if the current builder has right size, and otherwise falls back to ToImmutable()/Clear() if not. I would really love it if we added this to the BCL itself.
varbuilder=ImmutableArray.CreateBuilder<string>(/* max possible values */42);foreach(varxinthingGettingMapped){if(x.Frob)builder.Add(x);}returnbuilder.ToImmutableAndClear();
Alternative Designs
No response
Risks
No response
Reacted by Sergio Pedri, kronic, Monica S., Egor Bogatov, Wei Zheng, NN, Joe4evr and Tan90909090
The challenge is that MoveToImmutable() results in Capacity becoming 0, while ToImmutable(); Clear(); would preserve the capacity. This can result in cases where we need go through various resize cycles, making the Capacity == Count potentially more expensive.
Activity
Sergio0694 commentedon Jul 21, 2022
I also use something like this quite often in my generators and would very much welcome this API 🙂
Nit: the proposal says
ToImmutableAndClearbut the example usesToImmutableAndFree, old snippet?333fred commentedon Jul 21, 2022
No, force of habit. Roslyn also pools builders.
eiriktsarpalis commentedon Jul 22, 2022
Sounds useful enough. If we do add such a method, we might want to explicitly document that any perf benefits are predicated on
Capacity == Count.terrajobst commentedon Aug 16, 2022
Video
The challenge is that
MoveToImmutable()results inCapacitybecoming0, whileToImmutable(); Clear();would preserve the capacity. This can result in cases where we need go through various resize cycles, making theCapacity == Countpotentially more expensive.bartonjs commentedon Sep 6, 2022
Video