<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 = JSON.parse(JSON.stringify(MyObject));
myCopy = recursiveDeepCopy(MyObject);
myCopy = structuredClone(MyObject)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash CloneDeep | |
Json Clone | |
recursiveDeepCopy | |
structuredClone |
Test name | Executions per second |
---|---|
Lodash CloneDeep | 616432.4 Ops/sec |
Json Clone | 524355.4 Ops/sec |
recursiveDeepCopy | 2202011.2 Ops/sec |
structuredClone | 242811.3 Ops/sec |
The benchmark provided assesses four different methods for creating a deep copy of an object in JavaScript. Each method is tested in terms of its performance, measured by executions per second.
Lodash CloneDeep (myCopy = _.cloneDeep(MyObject);
):
JSON Clone (myCopy = JSON.parse(JSON.stringify(MyObject));
):
Date
objects, undefined
, or circular references.Recursive Deep Copy (myCopy = recursiveDeepCopy(MyObject);
):
Structured Clone (myCopy = structuredClone(MyObject);
):
Date
, Map
, Set
, ArrayBuffer
, and Blob
.The latest benchmark results indicate the following performance in terms of executions per second:
Alternatives to the methods tested include:
Object.assign
or the spread operator ({...obj}
) for shallow copying.Understanding these options allows developers to choose the most appropriate method for their specific application needs.