<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>
<script src='https://cdn.jsdelivr.net/npm/lodash/lodash.js'></script>
state = {
data: {
data1: {
data2: 'test'
}
}
};
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 |
---|---|
Produce | |
CloneDeep |
Test name | Executions per second |
---|---|
Produce | 566170.2 Ops/sec |
CloneDeep | 2234528.2 Ops/sec |
The benchmark under consideration compares two approaches for updating nested state objects in JavaScript: using Lodash's cloneDeep
method versus Immer's produce
function. Both libraries are widely adopted for handling immutable data in JavaScript applications, particularly in state management for frameworks like React.
Lodash:
cloneDeep
method is specifically used to create a deep copy of an object, which means it recursively duplicates each level of the object structure.Immer:
produce
method, which accepts a draft state and return a modified copy of it while tracking changes made to the draft.CloneDeep:
state
object and then mutates the copied object to update the nested value (data.data1.data2
).const result = _.cloneDeep(state);
result.data.data1.data2 = 'updated';
Produce:
produce
function, which creates a draft of the state object. It mutates the draft directly and returns the new state.const result = immer.produce(state, draft => { draft.data.data1.data2 = 'updated'; });
From the benchmark results provided, we see significant performance differences:
This suggests that cloneDeep
is approaching two and a half times faster than produce
in this specific scenario. The performance of these methods can vary widely depending on the structure and size of the object being manipulated. For shallow structures or objects where performance is critical, cloneDeep
may outperform produce
, but it incurs a cost in memory usage.
...
or Object.assign()
can be utilized, but they do not handle deeply nested structures as cloneDeep
or produce
do.In summary, the choice between CloneDeep
and Produce
fundamentally hinges on the specific use case—performance needs, memory management, and the complexity of the state shape. Each approach has its strengths and weaknesses, which engineers should assess based on their application's needs.