<script src="https://cdn.jsdelivr.net/npm/immer@3.1.3/dist/immer.umd.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
<script src="https://cdn.jsdelivr.net/npm/uuid@8.3.2/dist/umd/uuidv4.min.js"></script>
const numSiblings = 500;
const depth = 5;
state = {
data: {
data1: {
data2: 'test',
siblings: Array.from({
length: numSiblings
}).map(() => ({
id: uuidv4()
})),
children: Array.from({
length: depth
}).map(() => ({
id: uuidv4(),
data: {
data1: {
data2: 'test',
siblings: Array.from({
length: numSiblings
}).map(() => ({
id: uuidv4()
})),
children: Array.from({
length: depth
}).map(() => ({
id: uuidv4(),
data: {
data1: {
data2: 'test',
siblings: Array.from({
length: numSiblings
}).map(() => ({
id: uuidv4()
})),
children: Array.from({
length: depth
}).map(() => ({
id: uuidv4(),
data: {
data1: {
data2: 'test',
siblings: Array.from({
length: numSiblings
}).map(() => ({
id: uuidv4()
})),
},
},
})),
},
},
})),
},
},
})),
},
data3: Array.from({
length: 1000
}).map(() => document.createElement('div')),
},
};
const result = immer.produce(state, draft => { draft.data.data1.data2 = 'updated' })
const result = _.cloneDeep(state);
result.data.data1.data2 = 'updated';
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
immer.produce() | |
_.cloneDeep |
Test name | Executions per second |
---|---|
immer.produce() | 394618.5 Ops/sec |
_.cloneDeep | 23.5 Ops/sec |
I'll break down the benchmark definition and explain what's being tested, compared options, pros and cons, library usage, and other considerations.
Benchmark Definition:
The benchmark measures the performance of two functions: immer.produce
and _.cloneDeep
. Both functions are used to create deep copies of complex data structures.
What's being tested?
Comparison options:
The benchmark compares two approaches:
Pros and Cons:
Library usage:
The benchmark uses two libraries:
immer.produce
function for creating shallow copies of objects while updating specific properties._cloneDeep
function for recursively creating deep copies of entire objects or arrays.Other considerations:
uuidv4
library is used to generate unique IDs for each object or array element.immer.umd.min.js
and lodash.min.js
files are included in the benchmark setup code to ensure that both libraries are loaded correctly.Alternatives:
If you need to create deep copies of objects while preserving nested structures, consider using:
Keep in mind that these alternatives may have performance implications or limitations, especially when dealing with large data structures.