Last active
May 25, 2021 12:17
-
-
Save kevduc/74856214b493663242ba581c234bc4ae to your computer and use it in GitHub Desktop.
This file contains 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
const measure = (f, sampleSize, ...args) => { | |
const start = Date.now() | |
for (let i = 0; i < sampleSize; i++) f(...args) | |
return (Date.now() - start) / sampleSize | |
} | |
const perfDiff = (value1, value2) => (100 * (value1 - value2)/value1).toFixed(2) + '%' | |
const callback = (_,i) => i | |
const createArrayFillMapMethod = (size) => Array(size).fill().map(callback) | |
const createNewArrayFillMapMethod = (size) => new Array(size).fill().map(callback) | |
const createArrayFromMethod = (size) => Array.from({length: size}, callback) | |
const results = [] | |
const sampleSize = 1e5 | |
for (let size = 1; size <= 1e4; size *= 10) { | |
console.log(`Size ${size}...`) | |
const arrayFillMapMethodMeasure = 1000 * measure(createArrayFillMapMethod, sampleSize, size) // in µs | |
const newArrayFillMapMethodMeasure = 1000 * measure(createNewArrayFillMapMethod, sampleSize, size) // in µs | |
const arrayFromMethodMeasure = 1000 * measure(createArrayFromMethod, sampleSize, size) // in µs | |
// We use createArrayFillMapMethod as a reference to measure performance improvement | |
// - positive perfDiff => performance improvement | |
// - negative perfDiff => performance decrease | |
const perfDiff1 = perfDiff(arrayFillMapMethodMeasure, newArrayFillMapMethodMeasure) | |
const perfDiff2 = perfDiff(arrayFillMapMethodMeasure, arrayFromMethodMeasure) | |
results.push({size, arrayFillMapMethodMeasure, newArrayFillMapMethodMeasure, perfDiff1, arrayFromMethodMeasure, perfDiff2}) | |
console.table(results) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On
Windows 10
with a CPUIntel(R) Celeron(R) N4000 @ 1.10GHz
usingnode v15.10.0
❌
Array.from(...)
is 3 to more than 10 times slower to execute than the other 2 methodsLooks like
new Array()
is faster thanArray()
(need more data points)