<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/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,
jayson: {
stringify: 'JSON.stringify() method converts a JavaScript value to a JSON string....',
parse: 'JSON.parse() method parses a JSON string...',
},
deeplyNested: {
a: { b: { c: { d: { e: { f: { g: { h: { i: '10 levels deep' } } } } } } } }
},
};
var myCopy = null;
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Json clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 166234.5 Ops/sec |
Json clone | 211285.7 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark compares two methods for creating a deep copy of an object: JSON.parse(JSON.stringify(MyObject))
(using the built-in JSON
API) and _.cloneDeep(MyObject)
(using the Lodash library).
What are we testing?
We're testing which method is faster and more efficient in terms of execution speed.
Options compared
There are two options being compared:
JSON
API to create a deep copy of the object. It serializes the object, converts it to a string using JSON.stringify()
, and then parses the resulting string back into an object using JSON.parse()
. This approach can be slow for large objects due to the overhead of serialization and deserialization.cloneDeep()
function, which is specifically designed for creating deep copies of objects.Pros and Cons
Library usage
The benchmark uses the Lodash library (https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js
).
Special JS feature or syntax
None mentioned in this benchmark.
Other alternatives
There are other methods for creating deep copies of objects, such as:
Object.assign()
and recursively copying propertiesHowever, these alternatives may not be as efficient or optimized as the Lodash cloneDeep()
method.
In summary, this benchmark compares two methods for creating deep copies of objects: using the built-in JSON
API and using the Lodash library's cloneDeep()
. The Lodash approach is likely to be faster and more efficient due to its optimization for deep copy operations.