zoukankan      html  css  js  c++  java
  • 原子属性和使用互斥锁实现的属性的性能对比

    代码:

    #import "ViewController.h"
    
    extern uint64_t dispatch_benchmark(size_t count, void (^block)(void));
    
    @interface ViewController ()
    
    // 原子属性 - 互斥锁实现
    @property (strong, nonatomic) NSObject *obj1;
    
    // 原子属性 - 自旋锁实现
    @property (strong, atomic) NSObject *obj2;
    
    @end
    
    @implementation ViewController
    
    - (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
        
        size_t count = 1000000;
        
        // 性能测试 - 模拟原子属性
        uint64_t time1 = dispatch_benchmark(count, ^{
            self.obj1 = [[NSObject alloc] init];
        });
        NSLog(@"模拟的原子属性 = %llu ns", time1);
        
        // 性能测试 - 原子属性
        uint64_t time2 = dispatch_benchmark(count, ^{
            self.obj2 = [[NSObject alloc] init];
        });
        NSLog(@"原子属性 = %llu ns", time2);
    }
    
    // 重写set方法
    - (void)setObj1:(NSObject *)obj1 {
        // 使用互斥锁模拟原子属性
        @synchronized(self) {
            _obj1 = obj1;
        }
    }
    
    @end

    输出:

    模拟的原子属性 = 345 ns
    原子属性 = 192 ns

    总结:

    原子属性比使用互斥锁实现的属性性能更好。

  • 相关阅读:
    JavaScript获取浏览器高度和宽度值
    机器学习2
    2014.7.23
    2014.7.22
    STM32 定时器
    STM32 外部中断
    STM32--systick延时
    STM32 时钟
    输入捕获
    DAC
  • 原文地址:https://www.cnblogs.com/xwoder/p/4720733.html
Copyright © 2011-2022 走看看