Test name | Executions per second |
---|---|
spread ... | 6190795.0 Ops/sec |
slice() | 18844398.0 Ops/sec |
splice(0) | 11996991.0 Ops/sec |
concat() | 18391764.0 Ops/sec |
JSON.parse(JSON.stringify()) | 1767793.8 Ops/sec |
Custom function | 906768.8 Ops/sec |
Lodash.cloneDeep() | 435693.6 Ops/sec |
jQuery.extend(true) | 700202.3 Ops/sec |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true"
// Shallow copies: [], {}, function () {}
const arr2 = [ arr1 ];
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true"
// Shallow copies: [], {}, function () {}
const arr2 = arr1.slice();
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true"
// Shallow copies: [], {}, function () {}
const arr2 = arr1.splice(0);
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true"
// Shallow copies: [], {}, function () {}
const arr2 = arr1.concat();
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true", [], {}
// Shallow copies: function () {}
const arr2 = JSON.parse(JSON.stringify(arr1));
function copy(aObject) {
// Prevent undefined objects
// if (!aObject) return aObject;
let bObject = Array.isArray(aObject) ? [] : {};
let value;
for (const key in aObject) {
// Prevent self-references to parent object
// if (Object.is(aObject[key], aObject)) continue;
value = aObject[key];
bObject[key] = (typeof value === "object") ? copy(value) : value;
}
return bObject;
}
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true", [], {}, function () {}
const arr2 = copy(arr1);
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true", [], {}, function () {}
const arr2 = _.cloneDeep(arr1);
const arr1 = [ true, 1, "true", [], {}, function () {} ];
// Deep copies: true, 1, "true", [], {}, function () {}
const arr2 = jQuery.extend(true, [], arr1);