Skip to content

Instantly share code, notes, and snippets.

@jherr
Created April 24, 2023 14:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jherr/384692f0c71edbb2702f2c5dd1befb32 to your computer and use it in GitHub Desktop.
Save jherr/384692f0c71edbb2702f2c5dd1befb32 to your computer and use it in GitHub Desktop.
Basic performance tests of the spread operator
const numberFormat = new Intl.NumberFormat("en-US", { style: "decimal" });
const TEST_ARRAY_SIZE = 1000;
const TEST_COUNT = 1000;
const pushUsingPush = (arr) => {
arr.push(5);
return arr;
};
const pushUsingSpread = (arr) => {
return [...arr, 5];
};
const unshiftUsingUnshift = (arr) => {
arr.unshift(5);
return arr;
};
const unshiftUsingSpread = (arr) => {
return [5, ...arr];
};
const copyUsingSpread = (arr) => {
return [...arr];
};
const copyUsingStructuredClone = (arr) => {
return structuredClone(arr);
};
const testOperation = (fn, title) => {
// Create the test arrays
const arrays = new Array(TEST_COUNT)
.fill(0)
.map(() => new Array(TEST_ARRAY_SIZE).fill(0).map(() => Math.random()));
// Run the function against every test array
const start = performance.now();
for (const arr of arrays) {
fn(arr);
}
const end = performance.now();
console.log(
`${title
.padEnd(27)
.replace("{count}", numberFormat.format(TEST_ARRAY_SIZE))}: ${(
(end - start) /
TEST_COUNT
).toFixed(3)} ms/op`
);
};
testOperation(copyUsingStructuredClone, `copy {count} / clone`);
testOperation(copyUsingSpread, `copy {count} / spread`);
testOperation(pushUsingPush, `push onto {count} / push`);
testOperation(pushUsingSpread, `push onto {count} / spread`);
testOperation(unshiftUsingUnshift, `unshift {count} / unshift`);
testOperation(unshiftUsingSpread, `unshift {count} / spread`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment