多線程中一次性執(zhí)行和互斥鎖都是我們用來保證數(shù)據(jù)安全的常用方法肾档,下面我們使用代碼來測試使用這兩種方法來保證數(shù)據(jù)安全的時(shí)候哪個(gè)效率更高择诈。
在這里我們使用這兩種方法來創(chuàng)建單例模式誓琼,并且大次數(shù)循環(huán)創(chuàng)建單例對象晌缘,看創(chuàng)建相同次數(shù)的單例對象的時(shí)候哪種方法用的時(shí)間要少一點(diǎn)长捧。
首先我們創(chuàng)建一個(gè)工具類。
然后在DBTool.h中聲明兩個(gè)創(chuàng)建單例的方法
@interface DBTool :NSObject
+(instancetype)sharedDBTool;
+(instancetype)sharedDBToolOnce;
@end
在DBTool.h中實(shí)現(xiàn)兩個(gè)創(chuàng)建單例的方法
@implementation DBTool
//使用互斥鎖創(chuàng)建單例
+(instancetype)sharedDBTool{
static id _instanceType;
@synchronized(self) {
if(_instanceType ==nil) {
_instanceType = [self new];
}
}
return_instanceType;
}
//使用一次執(zhí)行創(chuàng)建單例
+(instancetype)sharedDBToolOnce{
static id _instanceType;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
if(_instanceType ==nil) {
_instanceType = [self new];
}
});
return _instanceType;
}
@end
接著在ViewController.m中創(chuàng)建單例
#define laryNum10000000
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//在viewDidLoad方法中大次數(shù)循環(huán)創(chuàng)建單例放祟,計(jì)算兩種方法創(chuàng)建單例對象所需要的時(shí)間
//下面這個(gè)方法用于計(jì)算起始時(shí)間鳍怨,優(yōu)點(diǎn)是計(jì)算時(shí)間精確度高
//獲取代碼開始執(zhí)行時(shí)時(shí)間
CFAbsoluteTime begin =CFAbsoluteTimeGetCurrent();
for(int i =0; i<10,i++){
DBTool *tool = [DBTool sharedDBTool];
}
//獲取代碼結(jié)束執(zhí)行時(shí)時(shí)間
CFAbsoluteTime end =CFAbsoluteTimeGetCurrent();
//計(jì)算開始和結(jié)束的時(shí)間差,該時(shí)間差就是循環(huán)創(chuàng)建單例需要的時(shí)間
NSLog(@"%f",end- begin);
//使用一次執(zhí)行創(chuàng)建單例對象
CFAbsoluteTime begin2 =CFAbsoluteTimeGetCurrent();
for(int i =0; i<10,i++){
DBTool *tool = [DBTool sharedDBToolOnce];
}
CFAbsoluteTime end2 =CFAbsoluteTimeGetCurrent();
NSLog(@"%f",end2- begin2);
}
下面是循環(huán)創(chuàng)建十萬次單例時(shí)兩種方法的時(shí)間差
這是循環(huán)創(chuàng)建一千萬次單例時(shí)兩種方法的時(shí)間差
根據(jù)上面數(shù)據(jù)跪妥,我們可以做出判斷鞋喇,使用一次執(zhí)行創(chuàng)建單例對象比使用互斥鎖創(chuàng)建單例對象效率高。