Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Example 1 of slow and fast NSDictionary access
// Created by Benedikt Terhechte on 07.12.11.
#import <Foundation/Foundation.h>
#define AKeyPathDictionary(dictionary, A) [dictionary objectForKey:@A]
#define BKeyPathDictionary(dictionary, A, B) [AKeyPathDictionary(dictionary, A) objectForKey:@B]
#define CKeyPathDictionary(dictionary, A, B, C) [BKeyPathDictionary(dictionary, A, B) objectForKey:@C]
#define DKeyPathDictionary(dictionary, A, B, C, D) [CKeyPathDictionary(dictionary, A, B, C) objectForKey:@D]
#define EKeyPathDictionary(dictionary, A, B, C, D, E) [DKeyPathDictionary(dictionary, A, B, C, D) objectForKey:@E]
#define FKeyPathDictionary(dictionary, A, B, C, D, E, F) [EKeyPathDictionary(dictionary, A, B, C, D, E) objectForKey:@F]
#define GKeyPathDictionary(dictionary, A, B, C, D, E, F, G) [FKeyPathDictionary(dictionary, A, B, C, D, E, F) objectForKey:@G]
#define HKeyPathDictionary(dictionary, A, B, C, D, E, F, G, H) [GKeyPathDictionary(dictionary, A, B, C, D, E, F, G) objectForKey:@H]
#define PP_NARG(...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
#define PP_RSEQ_N() HKeyPathDictionary,GKeyPathDictionary,FKeyPathDictionary,EKeyPathDictionary,DKeyPathDictionary,CKeyPathDictionary,BKeyPathDictionary,AKeyPathDictionary,0
#define KeyPathDictionary(...) PP_NARG(__VA_ARGS__)(__VA_ARGS__)
int main (int argc, const char * argv[])
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *aDictionary = [NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObject: @"Magnus Enzensberger" 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:@""];
// The fast but ugly and cumbersome approach
// Benchmark: 1.53 sec.
[[[[aDictionary objectForKey:@"data"] objectForKey:@"likes"] objectForKey: @"data"] objectForKey: @"friend"];
// The fast and beautiful approach
// Benchmark: 1.55 sec.
KeyPathDictionary(aDictionary, "data", "likes", "data", "friend");
[pool release];
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment