JavaScript Jabber #243 Immutable.js with Lee Byron

In notebook:
Article Notes
Created at:
JavaScript Functional Programming Fundamentals libraries React

Immutable data structures

When you modify an element of a List or an Object, instead of modifying the input (e.g. Array.push) you return a new object.


Lee mentions as the biggest advantage of immutable data structures is that you can very easily create comparisons if the data structure has changed or not (basically a simple ==) which leads to great optimisiations when you are doing UI, especially with libraries such as React. A related optimisation technique is memoization where you don't have to recalculate the return value if you know that input to your function is the same.

isn't it slow, when using huge Lists for example?

In a naive implementation, where you just copy the whole list and only change one item, it would be slow.

But internally, immutable lists are Objects, and all the members that have not changed are recycled "wholesale". It means that all members that have not changed point to the same register in memory.

My note: in JavaScript primitives are passed as values, but Object members are passed as reference. So this kind of optimisation is built in the language: if you create a "new" Object from an existing one, and you only change one member, all the other members will point to the same register in memory as your old Object.

Speed difference (Big-O) of mutating a regular Array vs immutable

Mutating a regular Array is O of 1 (if the Array contains 100 items, it's still only 1 operation to change one item), with immutable array is O of log(n), so for an Array of 100 items it's about 2. So it's not O of n which would be 100.