<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>
var data = { items: {}, count: 0, keys: [] }
for (let index = 0; index < 100; index++) {
data[index] = { id: index, name: `ITEM-${index}`, value: Math.random() }
data.count++
data.keys.push(index)
}
var NEW_ITEM_ID = data.count +1
var produce = immer.default
data = produce(data, draft => {
draft.items[NEW_ITEM_ID] = { id: NEW_ITEM_ID, name: 'ITEM-NEW', value: 0 }
draft.counter++
draft.keys.push(NEW_ITEM_ID)
})
data = {
data,
items: {
data.items,
[NEW_ITEM_ID]: { id: NEW_ITEM_ID, name: 'ITEM-NEW', value: 0 }
},
count: data.count +1,
keys: [ data.keys, NEW_ITEM_ID]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
immer | |
shallow copy |
Test name | Executions per second |
---|---|
immer | 1211.9 Ops/sec |
shallow copy | 3085.2 Ops/sec |
Let's break down the provided JSON data and explain what is being tested, compared, and the pros and cons of each approach.
What is being tested?
The benchmark measures the performance difference between two approaches:
data
object, which means only the top-level properties are copied, while nested objects are referenced directly.immer
library is used to create a deep copy of the data
object, which means all nested properties are also copied.Options compared
The two options being compared are:
Pros and cons of each approach
Library and its purpose
The immer
library provides a simple and efficient way to create immutable, persistent versions of data structures. It is particularly useful when working with complex data that needs to be modified predictably.
In the provided benchmark, immer
is used to create a deep copy of the data
object by defining a function that recursively creates new objects for all nested properties.
Special JS feature or syntax
There doesn't seem to be any specific JavaScript feature or syntax being tested in this benchmark. The focus is on comparing two different approaches to copying data structures.
Other alternatives
If you were to implement your own shallow copy solution without using a library, you could do so by recursively iterating over the object's properties and creating new objects with the same values. For example:
function shallowCopy(data) {
const result = {};
for (const key in data) {
if (typeof data[key] === 'object') {
result[key] = shallowCopy(data[key]);
} else {
result[key] = data[key];
}
}
return result;
}
However, this approach would require manual implementation and might be less efficient than using a library like immer
.
Overall, the benchmark is designed to test the performance difference between two approaches to copying data structures: shallow copy versus immer.