Tips for High Performance Collection Looping in Objective-C

A common task in Cocoa programming is to loop through a collection of objects (e.g. an NSArray, NSSet or NSDictionary). This seemingly simple problem has a wide variety of solutions, many of them with subtle performance considerations.

The Need for Speed

First, a disclaimer: The raw speed of one Objective-C method versus another is one of the last things you should worry about when programming – the difference is unlikely to be dramatic enough to matter compared with other, more important considerations, such as code clarity and readability.

But not prioritising speed is no excuse for not understanding it. You should always learn the performance implications of the code you are writing so that on the rare occasions when it does matter, you’ll know what to do.

Also, in the case of looping, much of the time it doesn’t matter which technique you choose from a readability or clarity perspective, so you might as well choose the fastest. There’s no point writing code that is slower than it needs to be.

With that in mind, here are the options:

Continue reading