Last active
May 28, 2019 01:05
-
-
Save kbjr/1a551ddb3b59e9685b04bb051daef44c to your computer and use it in GitHub Desktop.
Simple benchmark showing performance regression in recent versions of Node.js
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 size = 32000000; | |
const rand = () => Math.random() * 100; | |
console.log('Generating test data...'); | |
let data = new Array(size); | |
for (let i = 0; i < size; i++) { | |
data[i] = rand(); | |
} | |
const run = () => { | |
console.log('Starting tests...'); | |
const benchmarks = [ | |
runMapReduce, | |
runForEach, | |
runForLoop, | |
runForLoopNoLength | |
]; | |
benchmarks.forEach((func) => { | |
const results = [ ]; | |
for (let i = 0; i < 3; i++) { | |
results[i] = func(); | |
} | |
console.log( | |
func.name.padEnd(20, ' ') + | |
formatDuration(results[0]) + | |
formatDuration(results[1]) + | |
formatDuration(results[2]) | |
); | |
}); | |
}; | |
const runMapReduce = () => runWithTimer(() => { | |
const result = data | |
.map((x) => x ** 2) | |
.reduce((memo, x) => memo + x, 0); | |
}); | |
const runForEach = () => runWithTimer(() => { | |
let result = 0; | |
data.forEach((x) => { | |
result += x ** 2; | |
}); | |
}); | |
const runForLoop = () => runWithTimer(() => { | |
let result = 0; | |
for (let i = 0; i < data.length; i++) { | |
result += data[i] ** 2; | |
} | |
}); | |
const runForLoopNoLength = () => runWithTimer(() => { | |
let result = 0; | |
for (let i = 0; i < size; i++) { | |
result += data[i] ** 2; | |
} | |
}); | |
const runWithTimer = (func) => { | |
const start = process.hrtime(); | |
func(); | |
const end = process.hrtime(); | |
return msDiff(start, end); | |
}; | |
const formatDuration = (ms) => { | |
return `${ms.toPrecision(6)}ms`.padEnd(12, ' '); | |
}; | |
const msDiff = (start, end) => { | |
const secondDiff = end[0] - start[0]; | |
const nanosecondDiff = end[1] - start[1]; | |
return (secondDiff + nanosecondDiff / 1e9) * 1000; | |
}; | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment