#readwise # Please Welcome ImmutableArray ![rw-book-cover](https://readwise-assets.s3.amazonaws.com/static/images/article2.74d541386bbf.png) ## Metadata - Author: [[devblogs.microsoft.com]] - Full Title: Please Welcome ImmutableArray - URL: https://devblogs.microsoft.com/dotnet/please-welcome-immutablearrayt/ ## Highlights - `ImmutableArray<T>` is a very thin wrapper around a regular array and thus shares all the benefits with them. We even made it a value type (struct) as it only has a single field which holds the array it wraps. This makes the size of the value type identical to the reference of the array. In other words: passing around an immutable array is as cheap as passing around the underlying array. Since it’s a value type, there is also no additional object allocation necessary to create the immutable wrapper, which can reduce GC pressure. - Complexities: | Operation | ImmutableArray | ImmutabeList | Comments | | --------- | -------------- | ------------ | --------------------------------------------------------------------------------- | | Create() | O(n) | O(n) | Requires to copy the input array to ensure the underlying array can’t be modified | | this[] | O(1) | O(log n) | Directly index into the underlying array | | Add() | O(n) | O(log n) | Requires creating a new array | - Reasons to use immutable array: Updating the data is rare or the number of elements is quite small (<16) you need to be able to iterate over the data in performance critical sections you have many instances of immutable collections and you can’t afford keeping the data in trees Reasons to stick with immutable list: Updating the data is common or the number of elements isn’t expected to be small Updating the collection is more performance critical than iterating the contents - In general, when all you need is an immutable array and you don’t plan on changing the data ever, use `ImmutableArray<T>`. If you need to update the data, use `ImmutableList<T>`. If you do update the data but think `ImmutableArray<T>` could perform better overall, you should try both and measure. Remember that designing for performance means to consider different trade-offs. It’s key to measure those in actual scenarios, under real-world workloads.