<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...'
}
};
var myCopy = null;
function recursiveDeepCopy(o) {
var newO,
i;
if (typeof o !== 'object') {
return o;
}
if (!o) {
return o;
}
if ('[object Array]' === Object.prototype.toString.apply(o)) {
newO = [];
for (i = 0; i < o.length; i += 1) {
newO[i] = recursiveDeepCopy(o[i]);
}
return newO;
}
newO = {};
for (i in o) {
if (o.hasOwnProperty(i)) {
newO[i] = recursiveDeepCopy(o[i]);
}
}
return newO;
}
myCopy = _.cloneDeep(MyObject);
myCopy = structuredClone(MyObject);
myCopy = recursiveDeepCopy(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash cloneDeep | |
Native structuredClone | |
recursiveDeepCopy | |
Json Clone |
Test name | Executions per second |
---|---|
Lodash cloneDeep | 1100075.5 Ops/sec |
Native structuredClone | 788286.4 Ops/sec |
recursiveDeepCopy | 5660588.5 Ops/sec |
Json Clone | 986942.6 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares the performance of four different methods to create a deep copy of an object:
structuredClone
(native method)cloneDeep
from Lodash libraryrecursiveDeepCopy
(custom implementation)JSON.parse(JSON.stringify())
Options Compared
Each option is being tested for its execution speed, measured in executions per second.
Pros and Cons of Each Approach:
structuredClone
.Other Considerations
When creating deep copies, it's essential to consider factors such as:
Library Descriptions
Special JS Feature/Syntax
structuredClone
is a new feature introduced in ECMAScript 2020 (ES12), which allows creating deep copies of objects.Object.prototype.toString.apply()
is a method to retrieve the type of an object, used in the custom implementation of recursiveDeepCopy
.In summary, the benchmark compares the performance of four different methods for creating deep copies of objects: native structuredClone
, Lodash's cloneDeep
, and two custom implementations (recursiveDeepCopy
and JSON.parse(JSON.stringify())
). The choice of method depends on factors like browser support, library usage, and personal preference.