使用对象和键迭代 NSArray 的最快方法
我有一个名为“objects”的 NSArray,其 arrayCount = 1000。迭代该数组大约需要 10 秒。有谁有更快的方法来迭代这个数组?
for (int i = 0; i <= arrayCount; i++) {
event.latitude = [[[objects valueForKey:@"CLatitude"] objectAtIndex:i] floatValue];
event.longitude = [[[objects valueForKey:@"CLongitude"] objectAtIndex:i] floatValue];
}
I have an NSArray called 'objects' below with arrayCount = 1000. It takes about 10 secs to iterate through this array. Does anyone have a faster method of iterating through this array?
for (int i = 0; i <= arrayCount; i++) {
event.latitude = [[[objects valueForKey:@"CLatitude"] objectAtIndex:i] floatValue];
event.longitude = [[[objects valueForKey:@"CLongitude"] objectAtIndex:i] floatValue];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
迭代 NSArray 的最快方法是使用 快速枚举。我的情况是:
The fastest way to iterate over an NSArray would be to use fast enumeration. I your case this would be:
看起来 valueForKey 返回的数组在每次迭代中都是相同的,因此尝试在循环外获取对它们的引用:
但是循环的意义何在?最后,它不只是将事件属性设置为两个数组中的最后一个值吗?另外,如果 arrayCount 是元素数量,则循环应达到 i
i
i
i
i
i
i
i
i
i
i
i
i
i
i arrayCount
而不是i <= arrayCount
。It looks like the arrays returned by valueForKey will be the same at every iteration so try obtaining a reference to them once outside the loop:
But what is the point of the loop? In the end, doesn't it just set the event properties to the last values in the two arrays? Also, if arrayCount is the number of elements then the loop should be up to
i < arrayCount
instead ofi <= arrayCount
.添加到这里其他人所说的,快速枚举更快,因为它迭代 C 数组,而使用 objectAtIndex: 访问索引具有 Objective C 对象消息传递的开销。可以将其视为立即向 NSArray 对象请求其所有内容,而不是单独请求每个对象。
enumerateObjectsUsingBlock: 方法几乎同样快。块的功能非常强大,因为您可以将一段代码分配给一个变量并将其传递。
我正在寻找实际的基准测试并发现了这个:
http://darkdust.net/writings /objective-c/nsarray-枚举-性能
Adding to what others have said here, fast enumeration is faster because it iterates a C array, whereas accessing indices using objectAtIndex: has the overhead of Objective C object messaging. Think of it as asking the NSArray object for all of its stuff at once, as opposed to asking for each object individually.
The enumerateObjectsUsingBlock: method is nearly just as fast. Blocks can be powerful because you can assign a chunk of code to a variable and pass it around.
I was looking for actual benchmarks and found this:
http://darkdust.net/writings/objective-c/nsarray-enumeration-performance