Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example 1 of slow and fast NSDictionary access
//
// slow_kvo_dictionary_example.m
//
// Created by Benedikt Terhechte on 07.12.11.
// appventure.me
//
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *aDictionary = [NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObject: @"Zaphod Beeblebrox" forKey:@"friend"]
forKey: @"data"]
forKey: @"likes"]
forKey: @"data"];
// All benchmarks on a 2.7Ghy i7 MBP
int i;
for(i=0;i<5000000; i++) {
// The slow & easy approach
// Benchmark: 11.93 sec.
[aDictionary valueForKeyPath:@"data.likes.data.friend"];
// The fast but ugly and cumbersome approach
// Benchmark: 1.53 sec.
[[[[aDictionary objectForKey:@"data"] objectForKey:@"likes"] objectForKey: @"data"] objectForKey: @"friend"];
}
[pool release];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment