UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Is it efficient to create many tasks?

Paul Hudson    @twostraws   

Updated for Xcode 15

Previously I talked about the concept of thread explosion, which is when you create many more threads than CPU cores and the system struggles to manage them effectively. However, Swift’s tasks are implemented very differently from threads, and so are significantly less likely to cause performance problems when used in large numbers, and in fact one of the Swift team who worked on it said that unless you’re creating over 10,000 tasks it’s not worth worrying about the impact of so many tasks.

That doesn’t mean creating so many tasks is necessarily the best idea. You might think that’s hard to do, but a task group calling addTask() inside a loop might create several hundred or even several thousand depending on what you were looping over. And that’s okay. Again, even if you’re creating well over 10,000 tasks it’s not likely to cause a problem as long as you know that’s what you’re doing – if that’s the architectural choice you’re making after evaluating the alternative.

So, broadly speaking you should feel free to create as many tasks as you want, but if you ever find yourself creating tasks to transform elements inside huge arrays you might want to double-check your performance using something like Instruments.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.