Comparing deep cloning methods (array of objects): Lodash <> Custom clone func <> JSON.parse <> structuredClone
Missing clone-deep
Date tested:
one year ago
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
Test name
Executions per second
Lodash
419265.4 Ops/sec
Custom function
506533.4 Ops/sec
JSON.parse
406973.3 Ops/sec
structuredClone
320974.8 Ops/sec
Benchmark definition (click to collapse):
HTML Preparation code:
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
Script Preparation code:
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; } var MyObject = [ { "key": "categories.id", "values": [ "7549d23f-ef1a-4e2a-9649-2b6ca3d7a2d0", "ef7504a4-97c9-4efa-a6d2-ec25ebc953c2" ] }, { "key": "variants.attributes.ageRangeFacets", "values": [ "6+", "9+" ] }, { "key": "variants.scopedPrice.currentValue.centAmount", "ranges": [ { "from": "0", "to": "2000" }, { "from": "10000", "to": "20000" } ] } ]; var myCopy = null;
Tests:
Lodash
myCopy = _.cloneDeep(MyObject);
Custom function
myCopy = recursiveDeepCopy(MyObject);
JSON.parse
myCopy = JSON.parse(JSON.stringify(MyObject));
structuredClone
myCopy = structuredClone(MyObject);
Open this result on MeasureThat.net