创建单利的类:
#import "YQConfig.h"
@implementation YQConfig
+(instancetype)config{
static YQConfig*instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance=[[YQConfig alloc]init];
});
return instance;
}
+(instancetype)configSync{
static YQConfig*instance;
@synchronized (self) {
if (instance==nil) {
instance=[[YQConfig alloc]init];
}
}
return instance;
}
@end
ViewController.m中使用demo来测试两种方法性能的差别:
-(void)demo{
//disptach_once
double time1=CFAbsoluteTimeGetCurrent();
for (int i=0; i<999*99; i++) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
YQConfig*config5=[YQConfig config];
});
}
double time2=CFAbsoluteTimeGetCurrent();
NSLog(@"dispatch: %f ",time2-time1 );
//同步锁
double time3=CFAbsoluteTimeGetCurrent();
for (int i=0; i<999*999; i++) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
YQConfig*config5=[YQConfig configSync];
});
}
double time4=CFAbsoluteTimeGetCurrent();
NSLog(@"同步锁:%f ",time4-time3 );
}
运行结果:
2016-07-19 13:34:39.363 单例模式[1058:311069] dispatch: 0.186492
2016-07-19 13:34:43.112 单例模式[1058:311069] 同步锁:3.745988
从运行结果就可以看出,单利中使用dispatch 的方法时间比 同步锁@synchronized 性能多出数倍之多
开发中单利使用的平率很大
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
});