liveBook · Manning

Structural sharing

As explained in Grokking Simplicity

Structural sharing is a data-structure technique in which multiple versions reuse references to common portions of their representation.

Structural sharing lets multiple immutable data structures reuse references to unchanged nested data. A shallow copy duplicates only the top level, so shared inner objects avoid unnecessary copying. section 6.13 section 6.14

Use copy-on-write when updating nested data:

  • Copy the outer structure, such as an array with slice() or an object with Object.assign(). section 6.14
  • Copy and replace only the changed object, leaving unchanged objects shared. section 6.18
  • Keep shared data immutable; otherwise the original and updated versions can affect each other. section 6.14

Updating a shopping cart

To change a t-shirt’s price, copy the cart array and the t-shirt object, then replace the item in the copied array. Unchanged shoes and socks remain shared. Only the changed item and the path leading to it require copies. section 6.17 section 6.18

How Grokking Simplicity covers it

How deep it goes
Explains shallow copies, shared references, nested update paths, and safety, while deferring specialized persistent structures.
Examples
Demonstrates shopping-cart price and quantity updates using array slices, Object.assign(), and nested replacement.
What it assumes
Assumes JavaScript arrays and objects, while defining nested data, shallow copies, and structural sharing from their examples.
What you can do after
Apply via JavaScript’s slice() and Object.assign() to implement copy-on-write updates for nested data.
How it connects
Connects structural sharing with immutable data structures, copy-on-write, shallow copies, and garbage collection.

Also explained in

Compare how 3 books explain structural sharing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.