遍历 NSDictionary 的键/值, enumerateKeysAndObjectsUsingBlock 比循环键和调用 objectForkey: 更有效吗?

发布于 2024-12-05 20:16:52 字数 549 浏览 0 评论 0原文

我需要遍历字典的所有键/值对并对这两个字段执行某些操作。我想知道什么更有效,传统的“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

相对绾红妆 2024-12-12 20:16:52

它们基本上是相同的——它们都是同步遍历。然而,以下将允许并发遍历,这会更快:

[self.dictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                              usingBlock:^(id key, id object, BOOL *stop) {

}];

They would be basically the same -- they are both synchronous traversals. However, the following would allow for concurrent traversal, which would be faster:

[self.dictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                              usingBlock:^(id key, id object, BOOL *stop) {

}];
混浊又暗下来 2024-12-12 20:16:52

您应该使用基于块的方法。这更快,因为 此处显示。特别是,它不需要在字典中进行额外的查找来获取值,从而节省了性能。然而,除非在相当大的字典上操作,否则性能提升可以忽略不计。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文