Test name | Executions per second |
---|---|
lodash cloneDeep | 597805.4 Ops/sec |
JSON.parse(JSON.stringify()) | 381959.1 Ops/sec |
recursiveDeepCopy | 740805.3 Ops/sec |
fastest-json-copy npm package | 506518.8 Ops/sec |
jsondiffpatch.clone() | 1750460.4 Ops/sec |
rfdc | 1760206.2 Ops/sec |
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/jsondiffpatch@0.4.1/dist/jsondiffpatch.umd.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/rfdc@1.3.0'></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;
var jsondiffpatchClone = jsondiffpatch.clone;
var rfdcClone = rfdc();
///////////////////////////////////////////////////////////////////
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;
}
//////////////////////////////////////////////////////////////////
// Use https://www.npmjs.com/package/fastest-json-copy
// Instead of the code below! It is the same thing, just minified.
var isArray=Array.isArray;function fastestJsonCopy(r){if(!r)return r;if(isArray(r)){for(var e=[],o=r.length,t=0;t<o;t++)e.push(fastestJsonCopy(r[t]));return e}if("object"==typeof r){var y=Object.keys(r),a=(o=y.length,{});for(t=0;t<o;t++){var c=y[t];a[c]=fastestJsonCopy(r[c])}return a}return r}
myCopy = _.cloneDeep(MyObject);
myCopy = JSON.parse(JSON.stringify(MyObject));
myCopy = recursiveDeepCopy(MyObject);
myCopy = fastestJsonCopy(MyObject);
myCopy = jsondiffpatchClone(MyObject);
myCopy = rfdcClone(MyObject);