iOS性能优化之一:在Objective-C中遍历集合的性能

When enumerating an NSArray:

Use for (id object in array) if enumerating forwards.
Use for (id object in [array reverseObjectEnumerator]) if enumerating backwards.
Use for (NSInteger i = 0; i < count; i++) if you need to know the index value, or need to modify the array.
Try [array enumerateObjectsWithOptions:usingBlock:] if your code might benefit from parallel execution.
When enumerating an NSSet:

Use for (id object in set) most of the time.
Use for (id object in [set copy]) if you need to modify the set (but it will be slow).
Try [set enumerateObjectsWithOptions:usingBlock:] if your code might benefit from parallel execution.
When enumerating an NSDictionary

Use [dictionary enumerateKeysAndObjectsUsingBlock:] most of the time.
Use for (id key in [dictionary allKeys]) if you need to modify the dictionary.
Try [dictionary enumerateKeysAndObjectWithOptions:usingBlock:] if your code might benefit from parallel execution.
Not only are these methods the fastest available, but they’re also all very clear and readable. So remember, sometimes it’s not a choice between writing clean code and fast code; you may find that you can get the best of both worlds.


from:Nick Lockwood  http://iosdevelopertips.com/objective-c/high-performance-collection-looping-objective-c.html

猜你喜欢

转载自mirthor.iteye.com/blog/2016998