Back to articles
32-Element Branching: How Scala Vectors Solve Immutable Memory Pressure
How-ToSystems

32-Element Branching: How Scala Vectors Solve Immutable Memory Pressure

via Dev.toDoogal Simpson

TL;DR: Traditional immutable arrays are slow because updating an element requires a full O(n) copy. Scala’s Vector solves this by using a 32-way branching trie. This enables structural sharing, allowing the collection to reuse most of the original memory and reducing complexity to an effectively constant O(log32 n). I have always found the overhead of immutability to be one of the most interesting engineering trade-offs. In an immutable context, you can’t mutate state; you have to return new state. This means that if you are adding an element to a standard array, you have to create a new array with all the previous elements plus your new one. If you are adding thousands of elements, your CPU spends more time shuffling pointers and allocating memory than running business logic. I want to look at how Scala solved this with the Vector, a data structure that is surprisingly elegant once you look under the hood. Why is O(n) memory allocation a problem for immutable state? O(n) allocation fo

Continue reading on Dev.to

Opens in a new tab

Read Full Article
26 views

Related Articles