Skip to content

Instantly share code, notes, and snippets.

@jeremyckahn
Last active December 15, 2020 04:22
Show Gist options
  • Save jeremyckahn/b97f326f7534cca4585322db9f6db040 to your computer and use it in GitHub Desktop.
Save jeremyckahn/b97f326f7534cca4585322db9f6db040 to your computer and use it in GitHub Desktop.
#!/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('')
})
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
@jeremyckahn
Copy link
Author

jeremyckahn commented Dec 15, 2020

See the analysis of this code here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment