<script crossorigin src="https://unpkg.com/immutable-assign@2.0.4/deploy/iassign.js"></script>
var state = {
hasChanged: false,
name: 'Default state',
tags: [],
nested: {
hasChanged: false,
name: 'Default nested state',
tags: [],
nested: {
hasChanged: false,
name: '',
tags: []
},
map: new Map()
},
map: new Map()
};
const s7 = iassign(state, s => {
s.hasChanged = true;
return s;
});
const s8 = iassign(s7, s => s.nested, nested => {
nested.hasChanged = true;
return nested;
});
const s9 = iassign(s8, s => s.tags, tags => {
tags.push('new tag');
return tags;
});
const s10 = iassign(state, s => {
s.hasChanged = true;
s.nested = iassign(s.nested, nested => {
nested.hasChanged = true;
return nested;
});
s.tags = iassign(s.tags, tags => {
tags.push('new tag');
return tags;
});
return s;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
// sequential calls | |
// nested calls |
Test name | Executions per second |
---|---|
// sequential calls | 243435.1 Ops/sec |
// nested calls | 687498.9 Ops/sec |
What is being tested?
The provided benchmark measures the performance of two approaches to assign new values to nested objects in JavaScript:
s7
is created by assigning a new value to hasChanged
, then s8
is created by assigning a new value to nested.hasChanged
, and so on.s7
is created by assigning a new value to hasChanged
, then immediately creating another object with an iassign
function that assigns a new value to nested.hasChanged
.Options being compared
The benchmark compares the performance of these two approaches:
Pros and Cons of each approach
Library and its purpose
The benchmark uses the iassign
library, which provides a simple way to create immutable objects by assigning new values to them. The library is likely used to simplify the assignment operations in the test cases.
Special JS feature or syntax
None mentioned in this explanation.
Other alternatives
There are other ways to achieve similar results without using the iassign
library, such as:
Object.assign()
method with objectsObject.create()
method and then assigning values to themHowever, these alternatives may introduce additional complexity and overhead compared to using a dedicated library like iassign
.