Created
December 7, 2011 20:34
-
-
Save terhechte/1444513 to your computer and use it in GitHub Desktop.
Example 1 of slow and fast NSDictionary access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Created by Benedikt Terhechte on 07.12.11. | |
// Appventure.me | |
// | |
#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:@"data.likes.data.friend"]; | |
// 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