1 .h文件:
sharedMyOperationBySynchronized是互斥锁方式创建单例的类方法
sharedMyOperationByDispatchOnce是GCD一次性执行方式创建单例的类方法:
@interface MyOperation : NSOperation
+ (instancetype)sharedMyOperationBySynchronized;
+ (instancetype)sharedMyOperationByDispatchOnce;
@end
2 .m文件:
@implementation MyOperation
+ (instancetype)sharedMyOperationBySynchronized{
static id _instanceType = nil;
@synchronized (_instanceType) {
_instanceType = [[MyOperation alloc]init];
}
return _instanceType;
}
+ (instancetype)sharedMyOperationByDispatchOnce{
static id _instanceType = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instanceType = [[MyOperation alloc]init];
});
return _instanceType;
}
@end
3 演示代码:
#import "ViewController.h"
#import "MyOperation.h"
#define ENOUGH_LARGE_NUMBER 10000
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
将两种获取单例对象分别放在For循环中,获取For循环前的精确时间,再获取For循环执行完毕后的精确时间,对比两种方式的效率
*/
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CFAbsoluteTime startTimeSync = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < ENOUGH_LARGE_NUMBER; i ++) {
MyOperation *operationBySynchronized = [MyOperation sharedMyOperationBySynchronized];
}
CFAbsoluteTime endTimeSync = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime startTimeGCD = CFAbsoluteTimeGetCurrent();
for (int i = 0; i < ENOUGH_LARGE_NUMBER; i ++) {
MyOperation *operationByDispatchOnce = [MyOperation sharedMyOperationByDispatchOnce];
}
CFAbsoluteTime endTimeGCD = CFAbsoluteTimeGetCurrent();
NSLog(@"sharedMyOperationBySynchronized:%f",endTimeSync - startTimeSync);
NSLog(@"sharedMyOperationByDispatchOnce:%f",endTimeGCD - startTimeGCD);
}
@end
4 输出结果:
2016-06-09 20:23:22.712 07-单例效率比较[2166:395895] sharedMyOperationBySynchronized:0.012765
2016-06-09 20:23:22.712 07-单例效率比较[2166:395895] sharedMyOperationByDispatchOnce:0.000792
For循环的次数越大,体现越明显