NSEnumerator性能vs for循环在Cocoa [英] NSEnumerator performance vs for loop in Cocoa

查看:261
本文介绍了NSEnumerator性能vs for循环在Cocoa的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果你有一个循环,修改循环中的项目的计数,使用NSEnumerator在集合是确保你的代码爆炸的最好的方法,但我想了解性能之间的折衷, NSEnumerator类和只是一个旧学校for循环

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 would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop

推荐答案

使用新的 ...)在Objective-C 2.0中的语法通常是最快的迭代集合的方法,因为它可以在堆栈上维护一个缓冲区,并获得批量的项目。

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.

使用 NSEnumerator 通常是最慢的方法,因为它经常复制被迭代的集合;对于不可变集合,这可以是便宜的(相当于 -retain ),但对于可变集合,它可以导致创建不可变的副本。

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.

做你自己的迭代 - 例如,使用 - [NSArray objectAtIndex:] - 通常会落在中间,因为你不会有潜在的复制

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 - 这个问题应该标记为Objective-C,而不是C,因为 NSEnumerator 是一个Cocoa类,新的 for(... in ...)语法特定于Objective-C 。)

(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.)

这篇关于NSEnumerator性能vs for循环在Cocoa的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆