Created
February 18, 2015 08:32
-
-
Save anonymous/52c3def9af04cdf2a3a7 to your computer and use it in GitHub Desktop.
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
#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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.