美文网首页iOS OC 学习手册iOS 开发 iOS Developer
IOS开发多线程--一次性执行和互斥锁效率比较

IOS开发多线程--一次性执行和互斥锁效率比较

作者: 断风刀 | 来源:发表于2016-08-03 23:33 被阅读183次

    多线程中一次性执行和互斥锁都是我们用来保证数据安全的常用方法,下面我们使用代码来测试使用这两种方法来保证数据安全的时候哪个效率更高。

    在这里我们使用这两种方法来创建单例模式,并且大次数循环创建单例对象,看创建相同次数的单例对象的时候哪种方法用的时间要少一点。

    首先我们创建一个工具类。

    然后在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);

    }

    下面是循环创建十万次单例时两种方法的时间差

    这是循环创建一千万次单例时两种方法的时间差

    根据上面数据,我们可以做出判断,使用一次执行创建单例对象比使用互斥锁创建单例对象效率高。

    相关文章

      网友评论

        本文标题:IOS开发多线程--一次性执行和互斥锁效率比较

        本文链接:https://www.haomeiwen.com/subject/vfkcsttx.html