Structural sharing in Javascript

Win Le
2 min readApr 20, 2023

--

Using the immutable data structure is a good idea for some scenarios where schema data isn’t changed, helping the program reduce allocated and memory. The structural sharing algorithm is used under the hood immutable and is also good at sharing data between multiple versions.

What is Structural Sharing?

Structural sharing provides a way to share data between objects that are not duplicated and reuse the parts unchanged parts of the data structure again instead of copying them.

When you update an object that ensures an immutable data structure, you need to create a new object from the original object and update it. But when you create a new object, you must allocate the new memory. In scenarios when the original object has many key-value and references to other objects, it’s very harmful and has terrible performance. And so, we use Structural Sharing can avoid it.

How does Structural Sharing implement in Javascript?

function update(obj, updateObj) {
// Clone new object from obj
const newObj = { ...obj };

// Update properties of the new object with the update object
for (const key in updateObj) {

// Check if the key property already exists in the original object
if (key in obj) {

// If the value is an object, recursively update it
if (typeof obj[key] === 'object' && typeof updateObj[key] === 'object') {
newObj[key] = update(obj[key], updateObj[key]);
} else {
// Otherwise, update the property with the update value
newObj[key] = updateObj[key];
}
} else {
// If the property does not exist in the original object, add it with the update value
newObj[key] = updateObj[key];
}
}

return newObj;
}

This is the example code applying structural sharing with Javascript.

--

--