Created
February 28, 2014 19:09
-
-
Save js/9277611 to your computer and use it in GitHub Desktop.
You shouldn't use objc exceptions for flow control, among many reasons they're a tad slow.
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
// Output on this particular Mac | |
// | |
// Exceptions took 5.054922 | |
// BOOL return + NSError took 0.251062 | |
// | |
#import <Foundation/Foundation.h> | |
#import <mach/mach_time.h> | |
static inline void TimeDuration(NSString *description, NSUInteger runs, dispatch_block_t block) | |
{ | |
mach_timebase_info_data_t info; | |
if (mach_timebase_info(&info) != KERN_SUCCESS) { | |
exit(1); | |
} | |
uint64_t start = mach_absolute_time (); | |
for (NSUInteger i = 0; i < runs; i++) { | |
block(); | |
} | |
uint64_t elapsed = mach_absolute_time () - start; | |
double duration = (double)(elapsed * info.numer / info.denom) / NSEC_PER_SEC; | |
NSLog(@"%@ time: %f", description, duration); | |
} | |
@interface Failer : NSObject | |
- (void)failUsingException; | |
- (BOOL)failUsingError:(NSError **)error; | |
@end | |
@implementation Failer | |
- (void)failUsingException { | |
@throw [NSException exceptionWithName:@"fail" reason:@"total fail" userInfo:nil]; | |
} | |
- (BOOL)failUsingError:(NSError *__autoreleasing *)error { | |
*error = [NSError errorWithDomain:@"com.fail.total" code:0 userInfo:nil]; | |
return NO; | |
} | |
@end | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
const NSUInteger runs = 1000000; | |
Failer *obj = [[Failer alloc] init]; | |
TimeDuration(@"Exceptions", runs, ^{ | |
@try { | |
[obj failUsingException]; | |
} | |
@catch (NSException *exception) { | |
// ... | |
} | |
}); | |
TimeDuration(@"BOOL return + NSError", runs, ^{ | |
NSError *error; | |
if (![obj failUsingError:&error]) { | |
// ... | |
} | |
}); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment