Skip to content

Instantly share code, notes, and snippets.

Created February 18, 2015 08:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/52c3def9af04cdf2a3a7 to your computer and use it in GitHub Desktop.
Save anonymous/52c3def9af04cdf2a3a7 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
void (^benchmark)(const char *str) = ^(const char *str) {
const long count = 10000000;
NSDate *start = [NSDate date];
for (long i = 0; i < count; i++) {
(void)[[NSString alloc] initWithUTF8String:str];
}
NSTimeInterval t = -[start timeIntervalSinceNow];
NSLog(@"Time to allocate @\"%s\" %ld times was %f seconds", str, count, t);
};
benchmark("hellohello"); //Tagged pointer
benchmark("hellohelQo"); //'Q' is not in the set of characters that are packed into tagged pointer strings, since it's uncommon, and NSString saves space by using <8 bits per character for tagged strings
benchmark("Foundation.framework"); //In the StringROM, a perfect hash table of commonly used strings built into the CoreFoundation binary
benchmark("Foundation.framewokk"); //Not in the ROM, and too long to be tagged
}
return 0;
}
/*
Output on a 1.8GHz mid-2011 MacBook Air:
2015-02-18 00:29:43.699 NSStringIsWeird[9934:939189] Time to allocate @"hellohello" 10000000 times was 0.689991 seconds
2015-02-18 00:29:46.637 NSStringIsWeird[9934:939189] Time to allocate @"hellohelQo" 10000000 times was 2.936201 seconds
2015-02-18 00:29:47.839 NSStringIsWeird[9934:939189] Time to allocate @"Foundation.framework" 10000000 times was 1.202736 seconds
2015-02-18 00:29:50.671 NSStringIsWeird[9934:939189] Time to allocate @"Foundation.framewokk" 10000000 times was 2.831387 seconds
*/
@al45tair
Copy link

For comparison, if you use -initWithString: with a constant CFString/NSString instead of doing -initWithUTF8String: with a C string, 10,000,000 allocations will take around 0.5 seconds on the machine mentioned in the comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment