美文网首页iOS底层原理
iOS底层-cache_t分析

iOS底层-cache_t分析

作者: 何必太轻浮 | 来源:发表于2020-09-18 03:23 被阅读0次

    在之前我们已经分析过类的结构了,也具体分析过其中的isa、bits,现在我要开始分析一下cache:缓存


    pic0

    cache 的主要作用是存储类的方法,只有调用后才会缓存哦,并不是一开始加载就缓存的

    @interface MCPerson : NSObject
    {
        NSString *nickName;
    }
    @property (nonatomic,copy) NSString *name;
    -(void)say1;
    -(void)say2;
    -(void)say3;
    -(void)say4;
    -(void)say5;
    -(void)say6;
    -(void)say7;
    -(void)say8;
    -(void)say9;
    -(void)say10;
    -(void)say11;
    -(void)say12;
    @end
    
    @implementation MCPerson
    -(void)say1{
        NSLog(@"%s",__func__);
    }
    -(void)say2{
        NSLog(@"%s",__func__);
    }
    -(void)say3{
        NSLog(@"%s",__func__);
    }
    -(void)say4{
        NSLog(@"%s",__func__);
    }
    -(void)say5{
        NSLog(@"%s",__func__);
    }
    -(void)say6{
        NSLog(@"%s",__func__);
    }
    -(void)say7{
        NSLog(@"%s",__func__);
    }
    -(void)say8{
        NSLog(@"%s",__func__);
    }
    -(void)say9{
        NSLog(@"%s",__func__);
    }
    -(void)say10{
        NSLog(@"%s",__func__);
    }
    -(void)say11{
        NSLog(@"%s",__func__);
    }
    -(void)say12{
        NSLog(@"%s",__func__);
    }
    @end
    
    

    开始断点调试


    pic2

    当第一个方法都没调用的时候断住

    (lldb) p/x MCPerson.class
    (Class) $0 = 0x00000001000034c8 MCPerson
    (lldb) p (cache_t*)0x00000001000034d8 //内存偏移16个字节,取出cache
    (cache_t *) $1 = 0x00000001000034d8
    (lldb) p *$1
    (cache_t) $2 = {
      _buckets = {
        std::__1::atomic<bucket_t *> = 0x000000010032e440 {
          _sel = {
            std::__1::atomic<objc_selector *> = (null)
          }
          _imp = {
            std::__1::atomic<unsigned long> = 0
          }
        }
      }
      _mask = {
        std::__1::atomic<unsigned int> = 0//分配空间为0
      }
      _flags = 32804
      _occupied = 0 //数量0
    }
    

    当第一个方法调用后断住

    2020-09-18 02:51:45.097235+0800 KCObjc[42706:2137752] -[MCPerson say1]
    (lldb) p *$1
    (cache_t) $3 = {
      _buckets = {
        std::__1::atomic<bucket_t *> = 0x0000000102900350 {
          _sel = {
            std::__1::atomic<objc_selector *> = ""
          }
          _imp = {
            std::__1::atomic<unsigned long> = 8376
          }
        }
      }
      _mask = {
        std::__1::atomic<unsigned int> = 3//开辟空间为3
      }
      _flags = 32804
      _occupied = 1//数量为1
    }
    (lldb) 
    

    打印缓存的方法,注意,这里的buckets()是返回数组的第一个元素,如果要第二个元素可以p $3.buckets()[1]

    (lldb) p $3.buckets()
    (bucket_t *) $4 = 0x0000000102900350
    (lldb) p *$4
    (bucket_t) $5 = {
      _sel = {
        std::__1::atomic<objc_selector *> = ""
      }
      _imp = {
        std::__1::atomic<unsigned long> = 8376
      }
    }
    (lldb) p $5.sel()
    (SEL) $6 = "say1"
    

    这里说明的确方法调用后会缓存到cache中来

    接下来再次调用余下的方法,直到最后一个方法

    (lldb) p *$1
    (cache_t) $8 = {
      _buckets = {
        std::__1::atomic<bucket_t *> = 0x00000001006489e0 {
          _sel = {
            std::__1::atomic<objc_selector *> = (null)
          }
          _imp = {
            std::__1::atomic<unsigned long> = 0
          }
        }
      }
      _mask = {
        std::__1::atomic<unsigned int> = 15//开辟的空间
      }
      _flags = 32804
      _occupied = 5//数量
    }
    

    如果一个一个断点慢慢走,会发现_occupied会不断重置然后递增,_mask的值也再不断增加,所以我们来看一下源码,了解一下其中的逻辑

    ALWAYS_INLINE
    void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)
    {
    #if CONFIG_USE_CACHE_LOCK
        cacheUpdateLock.assertLocked();
    #else
        runtimeLock.assertLocked();
    #endif
    
        ASSERT(sel != 0 && cls->isInitialized());
    
        // Use the cache as-is if it is less than 3/4 full
        mask_t newOccupied = occupied() + 1;
        unsigned oldCapacity = capacity(), capacity = oldCapacity;
    //    如果缓存为空,初始化capacity大小为4,occupied为1,mask_t = capacity -1
    //     or
    //     newOccupied + 1 <= 容量 /4 * 3 的时候不管
    //     or
    //     _occupied 重置为0 capacity = capacity * 2
        if (slowpath(isConstantEmptyCache())) {
            // Cache is read-only. Replace it.
            if (!capacity) capacity = INIT_CACHE_SIZE;
            reallocate(oldCapacity, capacity, /* freeOld */false);
        }
        else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
            // Cache is less than 3/4 full. Use it as-is.
        }
        else {
            capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
            if (capacity > MAX_CACHE_SIZE) {
                capacity = MAX_CACHE_SIZE;
            }
    //调用这个方法后会重置_occupied、_mask
            reallocate(oldCapacity, capacity, true);
        }
    
        bucket_t *b = buckets();
        mask_t m = capacity - 1;
        mask_t begin = cache_hash(sel, m);
        mask_t i = begin;
    
        // Scan for the first unused slot and insert there.
        // There is guaranteed to be an empty slot because the
        // minimum size is 4 and we resized at 3/4 full.
            do {
     // 如果该次序没有值则缓存进去;
    //如果已缓存则打断缓存过程;
    //否则在列表中按照次序寻找下一个可缓存的次序只到缓存成功
            if (fastpath(b[i].sel() == 0)) {
                incrementOccupied(); // 在这里增长_occupied,标识有新的方法被缓存了
                b[i].set<Atomic, Encoded>(sel, imp, cls);// 插入缓存
                return;
            }
            if (b[i].sel() == sel) {
                // The entry was added to the cache by some other thread
                // before we grabbed the cacheUpdateLock.
                return; // 如果已缓存则打断缓存过程
            }
        } while (fastpath((i = cache_next(i, m)) != begin));
    
        cache_t::bad_cache(receiver, (SEL)sel, cls);// 缓存发生意外
    }
    
    ALWAYS_INLINE
    void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
    {
        bucket_t *oldBuckets = buckets();
        bucket_t *newBuckets = allocateBuckets(newCapacity);
    
        // Cache's old contents are not propagated. 
        // This is thought to save cache memory at the cost of extra cache fills.
        // fixme re-measure this
    
        ASSERT(newCapacity > 0);
        ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
    //调用这个方法后,_occupied会被重置
        setBucketsAndMask(newBuckets, newCapacity - 1);
        
        if (freeOld) {
            cache_collect_free(oldBuckets, oldCapacity);
        }
    }
    
    #if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
    
    void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
    {
        // objc_msgSend uses mask and buckets with no locks.
        // It is safe for objc_msgSend to see new buckets but old mask.
        // (It will get a cache miss but not overrun the buckets' bounds).
        // It is unsafe for objc_msgSend to see old buckets and new mask.
        // Therefore we write new buckets, wait a lot, then write new mask.
        // objc_msgSend reads mask first, then buckets.
    
    #ifdef __arm__
        // ensure other threads see buckets contents before buckets pointer
        mega_barrier();
    
        _buckets.store(newBuckets, memory_order::memory_order_relaxed);
        
        // ensure other threads see new buckets before new mask
        mega_barrier();
        
        _mask.store(newMask, memory_order::memory_order_relaxed);
        _occupied = 0;//重置为0
    #elif __x86_64__ || i386
        // ensure other threads see buckets contents before buckets pointer
        _buckets.store(newBuckets, memory_order::memory_order_release);
        
        // ensure other threads see new buckets before new mask
        _mask.store(newMask, memory_order::memory_order_release);
        _occupied = 0;//重置为0
    #else
    #error Don't know how to do setBucketsAndMask on this architecture.
    #endif
    }
    

    总结:

    • 对象缓存是放在类的缓存列表中的。
    • 缓存列表本来为空,只有当第一次调用对象某一个实例时才会分配给一个缓存空间。
    • 缓存空间容量是弹性的,当容量达到一定程度时,- 缓存空间会重新分配,此时列表也会被清空。
    • 缓存列表中的方法缓存时乱序的,和缓存顺序及方法在类中的顺序无关。(当全部方法调用完后,从buckets数组中取,很多方法无法取出,而且是乱序的)
    • _occupied代表此时混存列表中已缓存方法的数量,每次都会重置;这里有疑问,下次继续深入了解,这个字段代表的含义
    • _mask和容量大小相关。

    相关文章

      网友评论

        本文标题:iOS底层-cache_t分析

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