Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>The block approach</strong> avoids running the lookup algorithm for <em>every key</em>:</p> <pre><code>[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) { NSLog(@"%@ =&gt; %@", key, value); }]; </code></pre> <p>Even though <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html"><code>NSDictionary</code></a> is implemented as a <a href="http://en.wikipedia.org/wiki/Hashtable">hashtable</a> (which means that the cost of looking up an element is <a href="http://en.wikipedia.org/wiki/Big_oh"><code>O(1)</code></a>), lookups still slow down your iteration by <em>a constant factor</em>.</p> <p>My measurements show that for a dictionary <code>d</code> of numbers ...</p> <pre><code>NSMutableDictionary* dict = [NSMutableDictionary dictionary]; for (int i = 0; i &lt; 5000000; ++i) { NSNumber* value = @(i); dict[value.stringValue] = value; } </code></pre> <p>... summing up the numbers with the block approach ...</p> <pre><code>__block int sum = 0; [dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) { sum += value.intValue; }]; </code></pre> <p>... rather than the loop approach ...</p> <pre><code>int sum = 0; for (NSString* key in dict) sum += [dict[key] intValue]; </code></pre> <p>... <strong>is about 40% faster</strong>.</p> <p><strong>EDIT</strong>: The new SDK (6.1+) appears to optimise loop iteration, so <strong>the loop approach is now about 20% faster than the block approach</strong>, at least for the simple case above.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload