Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloureiro/657facaf27a80bc9958121779793755e to your computer and use it in GitHub Desktop.
Save mloureiro/657facaf27a80bc9958121779793755e to your computer and use it in GitHub Desktop.
Test execution time of Array.fill() vs Array.push()
function generator() {
let id = 0;
return () => id++;
}
function arrayFill(times, generator, sortFn = () => 0) {
return Array(times)
.fill(null)
.map(generator)
.sort(sortFn);
}
function arrayOf(times, generator, sortFn = null) {
const result = [];
for (let i = 0; i < times; ++i) {
result.push(generator());
}
return sortFn
? result.sort(sortFn)
: result;
}
function test(items, testFunction, sortFn, type) {
const start = Date.now();
const result = testFunction(items, generator(), sortFn);
const end = Date.now();
console.log(type, `${(end - start)/1000}s`, result.length);
}
const totalItems = 10000000;
test(totalItems, arrayFill, undefined, 'arrayFill');
test(totalItems, arrayOf, undefined, 'arrayOf');
const sortFn = (a, b) => a > b ? 1 : -1;
test(totalItems, arrayFill, sortFn, 'arrayFill with sort');
test(totalItems, arrayOf, sortFn, 'arrayOf with sort');
// Result
// arrayFill 2.743s
// arrayOf 0.349s
// arrayFill with sort 8.824s
// arrayOf with sort 6.461s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment