Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Created June 21, 2022 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbreckmckye/4ef62164bbdb4739f68b87b71611803e to your computer and use it in GitHub Desktop.
Save jbreckmckye/4ef62164bbdb4739f68b87b71611803e to your computer and use it in GitHub Desktop.
Penalty of unnecessary async / await
async function addAwait (a, b) {
const resolved = await a
return a + b
}
function addOptimised (a, b) {
if (a instanceof Promise) {
return a.then(resolved => resolved + b)
} else {
return a + b
}
}
async function timeAwaited () {
const start = Date.now()
let val = 1
for (let i = 0; i < 999999; i++) {
val = addAwait(val, 1)
}
await val
const end = Date.now()
console.log('time awaited fn - ', end - start)
}
async function timeOptimised () {
const start = Date.now()
let val = 1
for (let i = 0; i < 999999; i++) {
val = addOptimised(val, 1)
}
await val
const end = Date.now()
console.log('time optimised fn -', end - start)
}
async function main() {
timeOptimised()
console.log('--------')
await timeAwaited()
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment