Blog Archives

The power of concurrency

Hi everyone, and welcome to Saturday night’s advanced session regarding concurrency in iOS.

We all know that some of Apple’s more powerful devices come equipped with multiple cores and we mostly just trust the operating system to utilize this advantage whenever possible, right? Well, turns out there are some cases where we need to explicitly tell the operating system – ‘hey, this code should be executed concurrently’ (iOS is great, but it’s not a magician). Today, we will discuss one of these cases – concurrent enumeration.

Let’s say we have a huge data collection of independent data points and that we wish to execute some heavy mathematical operation on each of them. Now the mathematical operation(s) we wish to apply on a single object is completely orthogonal to all other objects meaning – this is code that’s ideal for running concurrently between processor cores. The way to do this is to enumerate this data collection with the¬†enumerateObjectsWithOptions:usingBlock: method, like so:

[[arr copy] enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
    //Do some heavy mathematical stuff with 'num'
}];

Just to emphasise the performance gain in using this method rather than fast enumeration, check out the output of running a similar scenario on the iOS simulator (yes, that’s why you see 4 cores):

Using simple, fast enumeration:

Simple

Simple enumeration – takes about 5 seconds to run 10000 iterations. You can see that operations run on one core, while the others are simply kicking back with a beer.

 

Using block enumeration with the NSEnumerationConcurrent option:

Concurrent

Now THAT’S team spirit! About 0.5 seconds to run 1000000 iterations. Unbelievable performance gain.

 

That’s it for today! Hope you find creative, safe ways to use this technique and remember – with great power comes great responsibility, so don’t abuse this API by running things in parallel that shouldn’t.