<script src="https://cdnjs.cloudflare.com/ajax/libs/immer/9.0.5/immer.umd.production.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var MyObject = {
description: 'Creates a deep copy of source, which should be an object or an array.',
myNumber: 123456789,
myBoolean: true,
testarray: [{
name: 1
}, {
name: 2
}, {
name: 3
}],
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...'
}
};
var myCopy = null;
myCopy = immer.produce(MyObject, draft => { draft.jayson.parse = 'updated' })
myCopy = _.cloneDeep(MyObject);
myCopy.jayson.parse = 'updated'
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy.jayson.parse = 'updated'
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
immer | |
deepclone | |
Json.stringify |
Test name | Executions per second |
---|---|
immer | 240307.6 Ops/sec |
deepclone | 573483.1 Ops/sec |
Json.stringify | 508066.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three different approaches to create a deep copy of an object: Lodash cloneDeep
, JSON Clone
with Immer, and plain old JSON Clone
. The test case creates a complex object with nested arrays and objects, and then modifies the jayson.parse
property on the copy.
Options Compared
The three options being compared are:
JSON.parse(JSON.stringify())
.Pros and Cons
cloneDeep
is a well-tested and efficient way to create deep clones of objects, including arrays and objects.Other Considerations
The benchmark also tests the performance of each approach on different browsers and devices. This is likely to provide more realistic results, as it simulates real-world usage scenarios.
Library and Syntax
The Immer library is used in this benchmark to create an immutable data structure. The produce
function creates a new draft of the original object, which is then modified using the provided callback function.
Special JS Feature or Syntax
None mentioned.
Alternatives
If you need to create deep clones of objects, you can consider using other libraries like immer
(which is used in this benchmark), lodash
, or JSON Patch
. For simpler use cases, plain old JSON.parse(JSON.stringify())
may still be sufficient.