Operation Queue vs Dispatch Queue for iOS Application

五迷三道 提交于 2019-11-28 18:32:57

NSOperationQueue predates Grand Central Dispatch and on iOS it doesn't use GCD to execute operations (this is different on Mac OS X). It uses regular background threads which have a little more overhead than GCD dispatch queues.

On the other hand, NSOperationQueue gives you a lot more control over how your operations are executed. You can define dependencies between individual operations for example, which isn't possible with plain GCD queues. It is also possible to cancel operations that have been enqueued in an NSOperationQueue (as far as the operations support it). When you enqueue a block in a GCD dispatch queue, it will definitely be executed at some point.

To sum it up, NSOperationQueue can be more suitable for long-running operations that may need to be cancelled or have complex dependencies. GCD dispatch queues are better for short tasks that should have minimum performance and memory overhead.

EDIT: It seems the documentation about NSOperationQueue is outdated and it does use GCD on iOS 4.0 and later.

  • Prefer GCD where task is not much complex and optimum CPU performance is required.
  • Prefer NSOperationQueue where task is complex and requires canceling or suspending a block and dependency management.

GCD is a lightweight way to represent units of work that are going to be executed concurrently. You don’t schedule these units of work; the system takes care of scheduling for you. Adding dependency among blocks can be a headache. Canceling or suspending a block creates extra work for you as a developer!

NSOperation and NSOperationQueue add a little extra overhead compared to GCD, but you can add dependency among various operations. You can re-use operations, cancel or suspend them. NSOperation is compatible with Key-Value Observation (KVO); for example, you can have an NSOperation start running by listening to NSNotificationCenter.

NSOperation and NSOperationQueue are higher lever APIs, made on top of the GDC itself, to achieve the concurrency in an object oriented way.

For detailed explanation, refer this question: https://stackoverflow.com/questions/10373331/nsoperation-vs-grand-central-dispatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!