Run details:
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0
Firefox 98
Windows
Desktop
2 years ago
Test name Executions per second
Lodash cloneDeep 308934.2 Ops/sec
JSON parse 527771.0 Ops/sec
For loop 854503.8 Ops/sec
Recursive clone deep 3276768.8 Ops/sec
Recursive reduce clone deep 968480.6 Ops/sec
HTML Preparation code:
AخA
 
1
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
Script Preparation code:
x
 
var obj = {a: "hello", c: "test", num: 3, arr: [1, 2, 3, 4], anotherObj: {a: 35, str: "tester"}};
var deepClone = function(obj) {
    var out = null;
    
    if (Array.isArray(obj)) {
        out = [];
        for (var index = 0; index < obj.length; ++index) {
            var subArray = obj[index];
            out.push((typeof subArray === 'object') ? deepClone(subArray) : subArray);
        }
    } else {
        out = {};
        for (var key in obj) {
            var subObject = obj[key];
            out[key] = (typeof subObject === 'object') ? deepClone(subObject) : subObject;
        }
    }
    return out;
};
 function cloneArray(value) {
    var newArray;
    if (value && value.length) {
      newArray = [];
      for (var i = 0; i < value.length; i++) {
        if (typeof value[i] === 'object') {
          newArray[i] = Array.isArray(value[i]) ? cloneArray(value[i]) : cloneObject(value[i]);
        } else {
          newArray[i] = value[i];
        }
      }
    } else if (value === null) {
      newArray = null;
    }
    return newArray;
  }
  function cloneObject(value) {
    var newObject;
    if (value && typeof value === 'object' && Object.keys(value).length > 0) {
      newObject = {};
      for (var key in value) {
        if (typeof value[key] === 'object') { 
          newObject[key] = Array.isArray(value) ? cloneArray(value[key]) : cloneObject(value[key]);
        } else {
          newObject[key] = value[key];
        }
      }
    } else if (value && typeof value === 'object' && Object.keys(value).length === 0) {
      newObject = {};
    } else if (value === null) {
      newObject = null;
    }
    return newObject;
  }
function reduceDeepClone(obj) {
  return Object.keys(obj).reduce((v, d) => Object.assign(v, {
    [d]: (obj[d].constructor === Object) ? reduceDeepClone(obj[d]) : obj[d]
  }), {});
}
Tests:
  • Lodash cloneDeep

     
    testCopy =  _.cloneDeep(obj);
  • JSON parse

     
    testCopy = JSON.parse(JSON.stringify(obj));
  • For loop

     
    testCopy = cloneObject(obj);
  • Recursive clone deep

     
    testCopy = deepClone(obj);
  • Recursive reduce clone deep

     
    testCopy = reduceDeepClone(obj);