2025-02-08 16:54:31
,某些文章具有时效性,若有错误或已失效,请在下方留言。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.
之前我谈到了线程爆炸的概念,即您创建的线程数比 CPU 内核多得多,并且系统难以有效地管理它们。然而,Swift 的任务与线程的实现方式非常不同,因此在大量使用时,它们不太可能导致性能问题,事实上,参与其中的 Swift 团队之一表示,除非你创建了超过 10,000 个任务,否则不值得担心这么多任务的影响。
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.
这并不意味着创建这么多任务一定是最好的主意。你可能认为这很难做到,但是在循环中调用 addTask()
的任务组可能会创建数百甚至数千个,具体取决于你正在循环的内容。这没关系。同样,即使你正在创建超过 10,000 个任务,只要你知道这就是你正在做的事情,它也不可能导致问题 – 如果这是你在评估替代方案后做出的架构选择。
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.
所以,从广义上讲,你应该随意创建任意数量的任务,但如果你发现自己在创建任务来转换巨大数组中的元素,你可能想使用类似 Instruments 的东西仔细检查你的性能。