I found out that running async-await can be much slower in some scenarios.
<html>
<script>
function makeAPromise() {
return Promise.resolve(Math.random());
}
function usingPromises() {
const before = window.performance.now();
return makeAPromise().then((num) => {
const after = window.performance.now();
console.log('Total (promises): ', after-before, 'ms');
return num;
})
}
async function usingAwait() {
const before = window.performance.now();
const num = await makeAPromise();
const after = window.performance.now();
console.log('Total (await): ', after-before, 'ms');
return num;
}
function runBoth() {
usingAwait();
usingPromises();
}
runBoth();
</script>
<button onclick="usingPromises()">usingPromises</button>
<button onclick="usingAwait()">usingAwait</button>
<button onclick="runBoth()">both</button>
</html>
IMO, the console.log in usingPromises should print similar results to the one in usingAwait.
But in reality, I get:
Total (promises): 0.25 ms
Total (await): 2.065 ms
Also, after the page load, if I click on 'usingPromises' or 'usingAwait' button I get similar results for each of them. (both are fast when running alone)
Total (promises): 0.060000000026775524 ms
Total (await): 0.08999999999650754 ms
But if I click on the 'both' button, the 'await' version is ~3-4 times slower than the promises version.
I have a real application running lots of promises / async-await function on initialisations, and I found out that replacing some of the async-await functions to their "equal" promises version can shave significant loading time (~200ms).
Can someone explain why is that? Isn't async-await also using the same job queue as promises (micro task)? Are there best practices to when should promises should be used instead of async-await?
- Running on chrome 62 on mac
Thanks
Total (await): 0.07500000000004547 msandTotal (promises): 0.75 ms. Could be a hardware related thing. Async-Await is using Promises internally. - NikxDarunBothgives twisted results, because the promise resolutions are sequenced in the event queue: so one gets to print withconsole.logbefore the other, and it is thatconsole.logthat brings additional delay to the second. It would already be an improvement if you would definerunBothasPromise.resolve().then(usingAwait).then(usingPromises). - trincot