NSEnumerator performance vs for loop in Cocoa

前端 未结 3 667
眼角桃花
眼角桃花 2020-12-18 19:27

I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I w

3条回答
  •  情书的邮戳
    2020-12-18 20:08

    Using the new for (... in ...) syntax in Objective-C 2.0 is generally the fastest way to iterate over a collection because it can maintain a buffer on the stack and get batches of items into it.

    Using NSEnumerator is generally the slowest way because it often copies the collection being iterated; for immutable collections this can be cheap (equivalent to -retain) but for mutable collections it can cause an immutable copy to be created.

    Doing your own iteration — for example, using -[NSArray objectAtIndex:] — will generally fall somewhere in between because while you won't have the potential copying overhead, you also won't be getting batches of objects from the underlying collection.

    (PS - This question should be tagged as Objective-C, not C, since NSEnumerator is a Cocoa class and the new for (... in ...) syntax is specific to Objective-C.)

提交回复
热议问题