

((new Date().getTime() - t) Array.isArray(e) ? e.clone() : e)

That said, do not use the above if your array might include functions as it will return null.ĭocument.getElementById("log").textContent += data + "\n" Out of all of those, the only way to deep clone an array is by using JSON.parse(JSON.stringify(arr)).Tests were made back in 2018, so today most likely you'll get different result with current browsers.It is not 100% reliable however it can give you a bulk idea as for how long it takes to clone an existing array: function clone(fn) ) Ħ) 39.72ms -> clone(arr => JSON.parse(JSON.stringify(arr))) ħ) 99.80ms -> clone(arr => arr.map(i => i)) Ĩ) 259.29ms -> clone(arr => Object.assign(, arr)) ĩ) Maximum call stack size exceeded -> clone(arr => Array.of(.arr)) I made this very plain utility function to test the time that it takes to clone an array. Please note that these methods will clone the Array object itself, array contents however are copied by reference and are not deep cloned. They output milliseconds, lower is better. There has been a huuuge BENCHMARKS thread, providing following information:įor blink browsers slice() is the fastest method, concat() is a bit slower, and while loop is 2.4x slower.įor other browsers while loop is the fastest method, since those browsers don't have internal optimizations for slice and concat.īelow are simple scripts that you can copy-paste into your browser's console and run several times to see the picture. There are at least 6 (!) ways to clone an array:
