Nathan Day
Nathan Day

Reputation: 6047

seeking advise on performance hit of threads in iOS

I have been working on a JSON parser for a little while https://github.com/nathanday/ndjson that parsers a stream of bytes instead of a complete document and convert directly into CoreData entities or custom objects instead of the usual property list objects. I am close to a version 1.0 but I have gotten to a point where to support NSURLConnection connection properly and to make parsing zipped JSON byte streams easier I have to change the way my parse internally works so that it can be called repeated (with the NSData objects the NSURLConnectionDelegate didReceiveData: method for example). I have two choice that I can think of, the simplest is use a thread to wait on the next piece of data available, or alternately I can rewrite the parsing part of my code so that it can be repeatedly be called, picking up from where it last was by creating my own stake for the variables that need to be maintained between calls. Using threads is simplest as it doesn't require very little rewriting if any, but as this is supposed to be a library for general use I am concerned about creating more threads than needed on a resources constrained device like the iPhone. Of cause the other options will make the code more complicated and having to maintain my own stack will not be resource free. Does anybody have any good advice or maybe another possible options. Is creating threads expensive. Maybe someone can think of a creative way using block, or is it possible to call the NSRunLoop object to execute the next event (NSURLConnectionDelegate methods).

Upvotes: 1

Views: 191

Answers (1)

toasted_flakes
toasted_flakes

Reputation: 2509

Under iOS and OS X, Apple provides a great way to do threads without headache: Grand Central Dispatch. Threads aren't expensive, and the system take care of creating the threads for you.

You can use serial queues to process your data and then sync it on the main thread using blocks:

// create the queue that will process your data:
dispatch_queue_t dataProcessQueue = dispatch_queue_create("data process queue", NULL); // the name is there for debugging purposes
    //dispatch to the newly created queue, and do not wait for it to complete
    dispatch_async(dataProcessQueue, ^{
        //your asynchronous job
        dispatch_async(dispatch_get_main_queue(), ^{
            // the work that has to be done on your main thread using data from above
    });
});
// don't forget to release the queue
dispatch_release(dataProcessQueue);

If you need to do concurrent work, you should use concurrent queues.

Apple's documentation is here

Upvotes: 1

Related Questions