Last active
December 15, 2020 04:22
-
-
Save jeremyckahn/b97f326f7534cca4585322db9f6db040 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env node | |
/* eslint-disable no-console */ | |
const regularFunction = () => { | |
const a = Math.random() | |
const b = Math.random() | |
const c = Math.random() | |
return a + b + c | |
} | |
const closuredFunction = ((a, b, c) => () => { | |
a = Math.random() | |
b = Math.random() | |
c = Math.random() | |
return a + b + c | |
})() | |
;[10 ** 1, 10 ** 2, 10 ** 4, 10 ** 6, 10 ** 8].forEach(iterations => { | |
const regularFunctionStartTime = Date.now() | |
for (let i = 0; i < iterations; i++) { | |
regularFunction() | |
} | |
const regularFunctionEndTime = Date.now() | |
const closuredFunctionStartTime = Date.now() | |
for (let i = 0; i < iterations; i++) { | |
closuredFunction() | |
} | |
const closuredFunctionEndTime = Date.now() | |
console.log( | |
`Regular function: Completed ${iterations} iterations in ${regularFunctionEndTime - | |
regularFunctionStartTime}ms` | |
) | |
console.log( | |
`Closured function: Completed ${iterations} iterations in ${closuredFunctionEndTime - | |
closuredFunctionStartTime}ms` | |
) | |
console.log('') | |
}) |
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
Regular function: Completed 10 iterations in 0ms | |
Closured function: Completed 10 iterations in 0ms | |
Regular function: Completed 100 iterations in 0ms | |
Closured function: Completed 100 iterations in 0ms | |
Regular function: Completed 10000 iterations in 3ms | |
Closured function: Completed 10000 iterations in 2ms | |
Regular function: Completed 1000000 iterations in 27ms | |
Closured function: Completed 1000000 iterations in 34ms | |
Regular function: Completed 100000000 iterations in 1758ms | |
Closured function: Completed 100000000 iterations in 3403ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the analysis of this code here.