开发者

Traversing key/values of an NSDictionary, is enumerateKeysAndObjectsUsingBlock more efficient than looping keys and calling objectForkey:?

开发者 https://www.devze.com 2023-04-06 13:18 出处:网络
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

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 enumerateKeysAndObjectsUs开发者_如何学GoingBlock:^(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!


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) {

}];


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号