Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 222
Lio Avatar asked Sep 22 '11 14:09

Lio


People also ask

What is NSDictionary in Objective c?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.

How do you add value in NSMutableDictionary?

You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil). The simplified form mentioned above, usually solves problems OCLint (metric static code analysis).


1 Answers

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

}];
like image 164
Michael Frederick Avatar answered Oct 13 '22 21:10

Michael Frederick