I am making most of my basic types in my app, immutable. But should the collections be immutable too? To me, this seems like a huge overhead unless I am missing something.
I am talking about collections to hold Point3 values, etc which can be added as it goes at different times. So if there are 1M values in a collection, and you needed to delete 1 of them, you would have to create the same collection all over again, right?
The common use case for the immutable methods is a collection that is initialized from known values, and that never changes. Also consider using these methods if your data changes infrequently. For optimal performance, the immutable collections store a data set that never changes.
The datatypes like int, float, bool, str, tuple, and Unicode are immutable. Datatypes like list, set, dict are mutable.
Collections are all immutable, but implement java collections interfaces (and generics) for inspection. Mutation returns new collections.
ImmutableArray. Provides methods for creating an array that is immutable; meaning it cannot be changed once it is created. NuGet package: System.Collections.Immutable (about immutable collections and how to install)
Eric Lippert has a series on Immutability in C#, and if you read it all the way through he implements a couple different immutable collections:
Immutable collections are great, especially if your app already leverages immutable types or semantics.
.NET just shipped their first immutable collections, which I suggest you try out.
My favorite trick with collections is simply to never pass them around. If they only exist inside a single object, then making them immutable is mostly irrelevant (As long as your containing object doesn't change them then they won't change).
Usually your collection represents something, right? It's a collection of dogs or a collection of invoices...
Usually there is a thing you can do with a collection of dogs (Herd? neuter?) or a collection of invoices (pay?) There are virtually always operations that apply to the whole list of objects--operations that have functionality beyond the singular invoice.pay() (for instance, ensuring that the most important invoices are paid first), without a class around your collection, there is really no where to put those operations.
It also usually makes sense to have a few variables associated with your collection--and again without a wrapper you always end up putting those variables in some strange unnatural location.
It may seem strange at first but try it a couple times before you judge.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With