遍历 NSDictionary 的键/值, enumerateKeysAndObjectsUsingBlock 比循环键和调用 objectForkey: 更有效吗?
我需要遍历字典的所有键/值对并对这两个字段执行某些操作。我想知道什么更有效,传统的“foreach key”方法或使用 enumerateKeysAndObjectsUsingBlock: 的块方法。
这里有一个例子:
传统方法(块之前)
for (NSString* key in [self.dictionary allKeys] ) {
[self processKey:key value: [self.dictionary objectForKey:value ]];
}
块方法。
[self.dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[self processKey:key value:obj];
}];
我的直觉是使用块遍历键/值对更快,但我不确定,因为我不知道字典和特定块方法是如何实现的。
有什么想法吗?
提前致谢!
I need to traverse all key/values pairs of a dictionary and do something with both fields. I am wondering what is more efficient, the traditional 'foreach key' approach or the blocks approach using enumerateKeysAndObjectsUsingBlock:.
Here you have an example:
Traditional approach (before blocks)
for (NSString* key in [self.dictionary allKeys] ) {
[self processKey:key value: [self.dictionary objectForKey:value ]];
}
Blocks approach.
[self.dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[self processKey:key value:obj];
}];
My gut feeling is that traversing the key/value pairs using the block is faster, but I am not sure since I don't know how dictionaries and the particular block method is implemented.
Any thoughts?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们基本上是相同的——它们都是同步遍历。然而,以下将允许并发遍历,这会更快:
They would be basically the same -- they are both synchronous traversals. However, the following would allow for concurrent traversal, which would be faster:
您应该使用基于块的方法。这更快,因为 此处显示。特别是,它不需要在字典中进行额外的查找来获取值,从而节省了性能。然而,除非在相当大的字典上操作,否则性能提升可以忽略不计。
You should use the block based method. This is faster, as shown here. In particular, it does not require an extra lookup in the dictionary to grab the value, which saves performance. However, performance gains will be negligible unless operating on reasonably-large dictionaries.