
There are frequently memory benefits, too (as B, C, D etc will all share the bulk of their representation with A). Because A never changes, it’s drastically easier to reason about and makes a lot of code much, much simpler - for example, A becomes trivially thread-safe.

That’s really disappointing - that’s not how immutable data structures are supposed to work at all. If an immutable collection interface offers mutation methods, this is the expectation of how it’ll work.īut you’re right, the Kotlin implementation is backed by a mutable LinkedHashMap, which does a physical copy (it has to, because it’s mutable). So you have two cheap allocations, one for the hash table, one for the list node, and now you’ve made a logical copy of the map in O(1) time. The tail points at the chain from the original map. To add an item to an immutable HashMap, all you do is duplicate the hash table, where each chain points at the corresponding chain from the original map except that the one chain you need to modify gets a new list node added on the front.

Logically copying the map doesn’t necessitate physically copying the map.
