开发者

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 bes开发者_如何转开发t suited to filter it? Blocks or predicates?

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


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.


When talking about performance it’s hard to beat an experiment. We could argue a whole day about the various performance implications of blocks or whatever solution used, but it’s best when you measure on the actual data used in your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜