Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray filtering: in which case using predicates and which case using blocks?

Performance wise, on a relatively large array (so far the usual count for the original array is ±20000), which method is best suited to filter it? Blocks or predicates?

Most of the ivars of the contained objects are strings and I want to query those.

like image 446
jibay Avatar asked Feb 07 '11 13:02

jibay


1 Answers

There is one way that blocks could be faster:

  1. You use NSEnumerationConcurrent to enumerate the array.
  2. When you find an object that matches your condition, dispatch another block to a serial queue that adds the object to the result array. (You can't do this concurrently because NSMutableArrays are not thread safe.)

However, the documentation doesn't explicitly say that order will be preserved when enumerating concurrently. I think it's a good bet that it won't be. If the order of the array matters, you'd have to re-sort (if that's even possible), and you'd have to include that in any timing comparison.

The other ways are to non-concurrently enumerate using blocks and to filter using predicates. filterUsingPredicate: could be faster, since NSArray will have the opportunity to use internal knowledge to build the result array faster than repeated addObject: messages. But that's merely a possibility; the only way to know for sure would be to compare, and even then, the answer could change at any time (including in the same process, for different input arrays or different objects in the array).

My advice would be to implement it straightforwardly—using predicates—at first, and then use Instruments to see whether it's a performance problem. If not, clear code wins. If it is a performance problem, try concurrent enumeration.

like image 64
Peter Hosey Avatar answered Oct 14 '22 23:10

Peter Hosey