Created
February 8, 2022 19:24
-
-
Save EduardoRodriguesF/57f0c496dd3f05fcede519ad10265dc4 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
function comparePerformance(firstFunction, secondFunction, iterations = 1) { | |
const averageExecutionTime = (func) => { | |
const executions = []; | |
for (let i = 0; i < iterations; i++) { | |
const start = performance.now(); | |
func(); | |
const end = performance.now(); | |
executions.push(end - start); | |
} | |
const sum = executions.reduce((a, b) => a + b, 0); | |
return (sum / executions.length) || 0; | |
} | |
console.log('[PERFORMANCE] EXECUTING FIRST FUNCTION'); | |
const firstAverage = averageExecutionTime(firstFunction); | |
console.log('[PERFORMANCE] EXECUTING SECOND FUNCTION'); | |
const secondAverage = averageExecutionTime(secondFunction); | |
if (firstAverage < secondAverage) { | |
console.log('[PERFORMANCE] The FIRST function is faster by', firstAverage - secondAverage, 'ms'); | |
} else if (firstAverage > secondAverage) { | |
console.log('[PERFORMANCE] The SECOND function is faster by', firstAverage - secondAverage, 'ms'); | |
} else { | |
console.log('[PERFORMANCE] It\'s a draw! Both functions took the same execution time'); | |
} | |
console.log('[PERFORMANCE] first execution time:', firstAverage, 'ms'); | |
console.log('[PERFORMANCE] second execution time:', secondAverage, 'ms'); | |
} | |
// window.comparePerformance = comparePerformance; /* Descomente para usar no DevTools com mais facilidade. | |
export default comparePerformance; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment