<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
//const { fromJS } = require('immutable');
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
var im = Immutable.fromJS(data);
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]
}
im = im.set('items', im.get('items').set(NEW_ITEM_ID, { id: NEW_ITEM_ID, name: 'ITEM-NEW', value: 0 }));
im = im.set('count', im.count +1);
im = im.set('keys', im.get('keys').push(NEW_ITEM_ID));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
immer | |
shallow copy | |
Immutable |
Test name | Executions per second |
---|---|
immer | 1844.7 Ops/sec |
shallow copy | 3939.1 Ops/sec |
Immutable | 332015.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is tested?
MeasureThat.net is testing three approaches to update an object in JavaScript:
Array.prototype.push
works.Options compared
The benchmark is comparing the performance of these three approaches in creating and pushing a new item to an array-like object (data.items
). The options are:
immer
: Creates a new draft object and updates it using the immer
library.shallow copy
: Creates a new object that references the original object's properties, effectively copying its value but not its identity.Immutable
: Uses immutable data structures, where updating an object creates a new one with the updated values.Pros and cons of each approach
immer
since it only creates a reference to the original object's properties.Library usage
In this benchmark, immer
is used as a library to provide a safe and predictable way to mutate objects. The Immutable.fromJS
function creates an immutable instance from the original data, and immer.default
is used to create a new draft object.
Special JS feature or syntax
None mentioned in this benchmark.
Other alternatives
In addition to these three approaches, other alternatives for updating JavaScript objects include:
Array.prototype.push
with a loop, which can be slower than shallow copy.{ ...data, items: { ...data.items, [NEW_ITEM_ID]: { id: NEW_ITEM_ID, name: 'ITEM-NEW', value: 0 } } }
) or object destructuring, which can be slower than immutable approaches.Keep in mind that these alternatives may not provide the same level of thread-safety and predictability as immer
or immutable data structures.