Skip to content

Instantly share code, notes, and snippets.

@chearon
Last active December 21, 2017 19:38
Show Gist options
  • Save chearon/10c9026e845503b92ca70e3738ca90e1 to your computer and use it in GitHub Desktop.
Save chearon/10c9026e845503b92ca70e3738ca90e1 to your computer and use it in GitHub Desktop.
Array mutation comparison
const a = [];
let target = [];
function noop(){};
for (let i = 0; i < 500000; ++i) a.push(Math.random());
console.time("push(...)");
target.push(...a);
console.timeEnd("push(...)");
target = [];
console.time("push.apply()");
target.push.apply(target, a);
console.timeEnd("push.apply()");
target = [];
console.time("splice()");
target.unshift(0, 0);
target.splice.apply(target, a);
console.timeEnd("splice()");
console.time("for () target.push(item)");
for (let i = 0; i < a.length; ++i) target.push(a[i]);
console.timeEnd("for () target.push(item)");
target = [];
console.time("noop(...)");
noop(...a);
console.timeEnd("noop(...)");
target = [];
console.time("noop.apply()");
noop.apply(window, a);
console.timeEnd("noop.apply()");
// RESULTS:
//
// push(...): 45.85ms
// push.apply(): 6.32ms
// splice(): 0.26ms
// for () target.push(item): 224.12ms
// noop(...): 40.5ms
// noop.apply(): 2.4ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment