Updated for Xcode 14.2
Whenever we use await
to call an async function, we mark a potential suspension point in our code – we’re acknowledging that it’s entirely possible our function will be suspended, along with all its callers, while the work completes. In terms of performance, this is not free: synchronous and asynchronous functions use a different calling convention internally, with the asynchronous variant being slightly less efficient.
The important thing to understand here is that Swift cannot tell at compile time whether an await
call will suspend or not, and so the same (slightly) more expensive calling convention is used regardless of what actually takes place at runtime.
However, what happens at runtime depends on whether the call suspends or not:
That last part carries an important side effect: using await
will not cause your code to wait for one runloop to go by before continuing.
It’s a common joke that many coding problems can be fixed by waiting for one runloop tick to pass before trying again – usually seen as DispatchQueue.main.async { … }
in Swift projects – but that will not happen when using await
, because the code will execute immediately.
So, if your code doesn’t actually suspend, the only cost to calling an asynchronous function is the slightly more expensive calling convention, and if your code does suspend then any cost is more or less irrelevant because you’ve gained so much extra performance thanks to the suspension happening in the first place.
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.