Persistent vs Immutable Collections
You may have heard about a helpful new collections library added in Kotlinx, specifically the kotlinx.collections.immutable library. In that library there are Persistent
and Immutable
versions of common collection classes like List
. So which version should you use? Does it matter?
Persistent and Immutable #
A quick overview of terms is the best place to start before we cover guidelines. A Persistent
collection is one that can only be modified by making updates to the underlying data structures pointers which now link the unaffected parts of the collection with new updated parts. On the other hand, an Immutable
collection is one that cannot be changed under any circumstance. Once the collection exists, its contents are fixed. In most cases, including in the Kotlinx Immutable Collections library, Immutable
collections inherit from Persistent
collections.
Aside - Readonly Collections #
A brief aside, because you may be thinking something like "Hey! I thought Kotlin collections already were immutable? I know I can't make updates to a List
, only a MutableList
!". While this is technically correct, the default collections are only read only, that is to say the object cannot be modified, but says nothing about the underlying data structure implementation and how changes will affect that structure. So while Immutable
collections are also read only, Persistent
collections are not.
Conclusion #
In conclusion, what should you use? For general use, the built in read only base collections should cover all your use cases, there is additional overhead to copy and maintain an Immutable
or Persistent
collection as compared to the base collections. But if you need persistence, such as in the example of Compose rendering, you just need to ask if you want mutability on the collection. If yes, reach for Persistent
collections, if no, reach for Immutable
collections. Until next time, thanks!
Did you find this content helpful?
Please share this post and be sure to subscribe to the RSS feed to be notified of all future articles!
Want to go above and beyond? Help me out by sending me $1 on Ko-fi. It goes a long way in helping run this site and keeping it advertisement free. Thank you in advance!
- Previous: UI Eventing on Android
- Next: Dev Diary - September 2023