Async/Await Performance Implications – Part 2

In my last post, I discussed the fact that Async/Await pushes the async function onto the event table when the executing thread hits an await call. On the face of it, that means that a program using async/await doesn’t ‘freeze up’ when an asynchronous operation occurs.

I also pointed out that while the whole program doesn’t freeze, the async function is paused while it waits on the await line.

The next question is what that last bit means from a performance standpoint. Here is an example piece of code using callbacks, and setTimeout to simulate an API call or other asynchronous event:

const timeoutFunction = () => {
    setTimeout(()=> {
        console.log("Done");
    }, 5000)

    setTimeout(()=> {
        console.log("Done");
    }, 5000)

    setTimeout(()=> {
        console.log("Done");
    }, 5000)
}
timeoutFunction();

As far as output goes, there is a 5-second pause, and then three instances of “Done” being logged out right away, one right after the other.

Contrast that with this code:

const asyncTimeout = () => {
    return new Promise(function(resolve, reject) {
        setTimeout(resolve, 5000);
    }).then(() => {
        console.log("Done");
    })
}

const testAsync = async () => {
    await asyncTimeout();
    await asyncTimeout();
    await asyncTimeout();
}

testAsync();

This second block of code results in a 5-second pause, the logging of “Done”, another 5-second pause, the logging of “Done”, another 5-second pause, and then finally the third logging of “Done”.

Much like the second block of code in my last blog post, we can see that inside of the async function, execution is paused at each await statement, which means that you have 3 separate, 5-second pauses as compared to the first code-block using callback functions, in which the three, 5-second pauses have a nearly 100% overlap.

In summary:
As most of you have no-doubt already deduced, using async/await for a single asynchronous call has no performance hit against doing that same asynchronous operation as a callback.

When doing multiple asynchronous operations in a single function, if the asynchronous calls build on each other (meaning that data from the first call is needed to make the second call), then you lose nothing performance-wise by using async/await, and likely dramatically simplify how you construct your code.

However, if you need to make multiple un-related asynchronous calls, then you’re better off not putting them all in the same async function because doing so eliminates any overlap in the wait for the asynchronous calls to report back.

Leave a Reply