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