Skip to content

Instantly share code, notes, and snippets.

@dmiedema
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save dmiedema/45a9910ce19eeacbec80 to your computer and use it in GitHub Desktop.

Select an option

Save dmiedema/45a9910ce19eeacbec80 to your computer and use it in GitHub Desktop.
Because I was curious of the performance difference
| DispatchOnce | Static | |
|:--------------:|:-------:|:-------:|
| 107 | 342 | |
| 82 | 408 | |
| 86 | 365 | |
| 88 | 357 | |
| 98 | 375 | |
| 89 | 356 | |
| 90 | 357 | |
| 86 | 351 | |
| 91 | 362 | |
| 99 | 364 | |
| 91.6 | 363.7 | Average |
2014-12-13 15:53:36.646 tester[37460:195541] profile: dispatchOnce: 107 ms
2014-12-13 15:53:36.991 tester[37460:195541] profile: static: 342 ms
//
// main.m
// tester
//
// Created by Daniel on 12/13/14.
// Copyright (c) 2014 Daniel. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
@interface NSObject (Log)
- (void)logTimeTakenToRunBlock:(void (^)(void)) block withPrefix:(NSString*) prefixString;
@end
@implementation NSObject (Log)
- (void)logTimeTakenToRunBlock:(void (^)(void))block withPrefix:(NSString *)prefixString {
double a = CFAbsoluteTimeGetCurrent();
block();
double b = CFAbsoluteTimeGetCurrent();
unsigned int m = ((b-a) * 1000.0f); // convert from seconds to milliseconds
NSLog(@"profile: %@: %d ms", prefixString ? prefixString : @"Time taken", m);
}
@end
@interface UIColor (Thing)
+ (UIColor *)dispatchOnceColor;
+ (UIColor *)staticColor;
@end
@implementation UIColor (Thing)
+ (UIColor *)dispatchOnceColor {
static UIColor *clr = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
clr = [UIColor colorWithRed:150/255.0 green:125/255.0 blue:67/255.0 alpha:1];
});
return clr;
}
+ (UIColor *)staticColor {
return [UIColor colorWithRed:145/255.0 green:100/255.0 blue:200/255.0 alpha:1.0];
}
@end
int main(int argc, char * argv[]) {
@autoreleasepool {
NSObject *obj = [NSObject new];
[obj logTimeTakenToRunBlock:^{
for (NSInteger i = 0; i < 1000000; i++) {
UIColor *color = [UIColor dispatchOnceColor];
// NSLog(@"color - %@", color.debugDescription);
}
} withPrefix:@"dispatchOnce"];
[obj logTimeTakenToRunBlock:^{
for (NSInteger i = 0; i < 1000000; i++) {
UIColor *color = [UIColor staticColor];
// NSLog(@"color - %@", color.debugDescription);
}
} withPrefix:@"static"];
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment