views:

385

answers:

1

I have created one testing app for running deep counter loop. I run the loop fuction in background thread using performSelectorInBackground and also NSOperation subclass separately.

I am also using performSelectorOnMainThread to notify main thread within backgroundthread method and [NSNotificationCenter defaultCenter] postNotificationName within NSOperation subclass to notify main thread for updating UI.

Initially both the implementation giving me same result and i am able to update UI without having any problem. The only difference i found is the Thread count between two implementations.

The performSelectorInBackground implementation created one thread and got terminated after loop finished and my app thread count again goes to 1.

The NSOperation subclass implementation created two new threads and keep exists in the application and i can see 3 threads after loop got finished in main() function.

So, my question is why two threads created by NSOperation and why it didn't get terminated just like the first background thread implementation?

I am little bit confuse and unable to decide which implementation is best in-terms of performance and memory management.

Thanks

+3  A: 

It's likely the operation queue is keeping threads alive, waiting for new operations to appear.

You have to remember that the operation queue is designed to work efficiently with many operations, so creating and destroying threads for each operation is going to hurt performance. So what you are seeing is probably just the way the queue is designed to work by keeping a pool of threads alive.

Basically, as long as you are using the operation queue properly and according to the documentation I wouldn't worry about it.

Mike Weller
Thanks, so this means that i can reuse the same operation queue for several attempts for the same operation/loop or is there any way to drain the threads pool created by operation queue.
AmitSri
AmitSri: You can put as many operations as you want into a queue. You *can* throw away the queue and make a new one later, but there's not any performance reason to do that—the threads don't use any CPU time unless there's something running on them, so there's no reason to throw them away. (Check this in Activity Monitor if you don't believe me. And if you see that your app *is* using CPU time, profile in Instruments or Shark to see what it's using that time on.)
Peter Hosey