Created
June 21, 2022 14:18
-
-
Save jbreckmckye/4ef62164bbdb4739f68b87b71611803e to your computer and use it in GitHub Desktop.
Penalty of unnecessary async / await
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
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