Cocoa NSArray/NSSet: -makeObjectsPerformSelector: vs. fast enumeration

后端 未结 5 1034
臣服心动
臣服心动 2021-02-13 09:50

I want to perform the same action over several objects stored in a NSSet.

My first attempt was using a fast enumeration:

for (id item in myS         


        
5条回答
  •  日久生厌
    2021-02-13 10:34

    If pure speed is the only issue (i.e. you're creating some rendering engine where every tiny CPU cycle counts), the fastest possible way to iterate through any of the NSCollection objects (as of iOS 5.0 ~ 6.0) is the various "enumerateObjectsUsingBlock" methods. I have no idea why this is, but I tested it and this seems to be the case...

    I wrote small test creating collections of hundreds of thousands of objects that each have a method which sums a simple array of ints. Each of those collections were forced to perform the various types of iteration (for loop, fast enumeration, makeObjectsPerformSelector, and enumerateObjectsUsingBlock) millions of times, and in almost every case the "enumerateObjectsUsingBlock" methods won handily over the course of the tests.

    The only time when this wasn't true was when memory began to fill up (when I began to run it with millions of objects), after which it began to lose to "makeObjectsPerformSelector".

    I'm sorry I didn't take a snapshot of the code, but it's a very simple test to run, I highly recommend giving it a try and see for yourself. :)

提交回复
热议问题