Created
April 30, 2018 07:28
-
-
Save mloureiro/657facaf27a80bc9958121779793755e to your computer and use it in GitHub Desktop.
Test execution time of Array.fill() vs Array.push()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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