美文网首页iOS底层
类(三)-- cache_t分析

类(三)-- cache_t分析

作者: 过气的程序员DZ | 来源:发表于2020-09-18 02:58 被阅读0次

类(一)-- 底层探索
类(二)-- method归属
类(三)-- cache_t分析

cache_t作用

用来缓存通过对象调用过的方法。当再次调用的时候,能够快速的通过sel找到方法imp

cache_t结构

相关源码如下:

#if defined(__arm64__) && __LP64__
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_HIGH_16
#elif defined(__arm64__) && !__LP64__
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_LOW_4
#else
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_OUTLINED
#endif

struct cache_t {
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
    explicit_atomic<struct bucket_t *> _buckets;
    explicit_atomic<mask_t> _mask;
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
    explicit_atomic<uintptr_t> _maskAndBuckets;
    mask_t _mask_unused;
    
    // How much the mask is shifted by.
    static constexpr uintptr_t maskShift = 48;
    
    // Additional bits after the mask which must be zero. msgSend
    // takes advantage of these additional bits to construct the value
    // `mask << 4` from `_maskAndBuckets` in a single instruction.
    static constexpr uintptr_t maskZeroBits = 4;
    
    // The largest mask value we can store.
    static constexpr uintptr_t maxMask = ((uintptr_t)1 << (64 - maskShift)) - 1;
    
    // The mask applied to `_maskAndBuckets` to retrieve the buckets pointer.
    static constexpr uintptr_t bucketsMask = ((uintptr_t)1 << (maskShift - maskZeroBits)) - 1;
    
    // Ensure we have enough bits for the buckets pointer.
    static_assert(bucketsMask >= MACH_VM_MAX_ADDRESS, "Bucket field doesn't have enough bits for arbitrary pointers.");
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
    // _maskAndBuckets stores the mask shift in the low 4 bits, and
    // the buckets pointer in the remainder of the value. The mask
    // shift is the value where (0xffff >> shift) produces the correct
    // mask. This is equal to 16 - log2(cache_size).
    explicit_atomic<uintptr_t> _maskAndBuckets;
    mask_t _mask_unused;

    static constexpr uintptr_t maskBits = 4;
    static constexpr uintptr_t maskMask = (1 << maskBits) - 1;
    static constexpr uintptr_t bucketsMask = ~maskMask;
#else
#error Unknown cache mask storage type.
#endif
    
#if __LP64__
    uint16_t _flags;
#endif
    uint16_t _occupied;
    
    //省略后面代码
    ......
}

struct bucket_t {
private:
    // IMP-first is better for arm64e ptrauth and no worse for arm64.
    // SEL-first is better for armv7* and i386 and x86_64.
#if __arm64__
    explicit_atomic<uintptr_t> _imp;
    explicit_atomic<SEL> _sel;
#else
    explicit_atomic<SEL> _sel;
    explicit_atomic<uintptr_t> _imp;
#endif
    //省略后面代码
    ......
}
  • 结构体cache_t中进行了编译条件判断:

    • CACHE_MASK_STORAGE_OUTLINED:其它情况(本文主要研究方向,另外两种同理,但是稍微复杂)
    • CACHE_MASK_STORAGE_HIGH_16:代表arm64平台并且是64位设备
    • CACHE_MASK_STORAGE_LOW_4:代表arm64平台、非64位设备
  • _buckets:struct bucket_t类型,数组形式存储sel和imp。(注意,不同平台下,sel和imp顺序不一样。原因注释中有解释,就是一种针对不同平台的优化。)

  • _mask:mask_t类型。也是针对不同平台的定义的别名,源码如下:

    #if __LP64__
    typedef uint32_t mask_t;  // x86_64 & arm64 asm are less efficient with 16-bits
    #else
    typedef uint16_t mask_t;
    

    作用是记录当前已开辟的内存空间可用的最大值。

  • _flags:uint16_t类型,内部使用的标志位。

  • _occupied:uint16_t类型,表示缓存中已经占用数。如果缓存了一个方法,_occupied就设置为1。两个方法,则为2。

lldb调试

Person *p  = [Person alloc];
Class pClass = [Person class];
[p sayHello];
[p sayCode];
NSLog(@"%@",pClass);
  • 打印类的内存地址
  • cache_t cache在结构体中第三个位置,前两个是指针类型,分别是isasuperclass,所以内存便宜是16字节,转换16进制是10。因此在原地址上进行+10操作。
  • 得到cache_t *类型的$1,调用buckets()函数得到bucket_t *类型的$2
  • 调用sel()imp(pClass)函数,可以打印出缓存的方法的selimp
  • 通过指针偏移打印后面的缓存方法信息。
  • 通过打印$1中的值,能够看到目前_occupied的值是2,说明目前的缓存空间占用了2个位置,就是示例中调用过的两个方法被缓存了。

方法缓存的插入逻辑

对象调用方法会间接调用源码中的下面函数

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;
    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)) { // 4  3 + 1 bucket cache_t
        // Cache is less than 3/4 full. Use it as-is.
    }
    else {
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;  // 扩容两倍 4
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
        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();
            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);
}

源码的逻辑:

  • 首先进行cache是否为空的状态if (slowpath(isConstantEmptyCache())),然后对容器大小进行初始值赋值capacity = INIT_CACHE_SIZE,并且调用reallocate函数进行内存空间开辟
  • 然后进行容器大小的3/4判断,如果超过3/4,进行二倍扩容,调用reallocate函数开辟内存空间
  • 保证空间够用后,最后进行保存被调用方法的sel和imp:
    • 此处对sel进行哈希计算(哈希函数:sel转换成无符号的长整形 & 当前的可用空间大小mask),求出位置
    • 进行do-while循环,看看这个位置有没有值:
      • 没有值就插入
      • 有值进行sel比较,相等就直接返回,说明此方法已经缓存过;
      • 如果位置上有值,并且sel不相等,就对位置+1后 & 总空间大小mask,进行再次哈希(哈希冲突的开放地址法)。)。

相关文章

  • 类(三)-- cache_t分析

    类(一)-- 底层探索类(二)-- method归属类(三)-- cache_t分析 cache_t作用 用来缓存...

  • 类(一)-- 底层探索

    类(一)-- 底层探索类(二)-- method归属类(三)-- cache_t分析 这篇文章来探索类的底层 类探...

  • OC底层探究(5)-- cache_t分析

    cache_t的结构 在上一篇类的结构分析中, 我们从类的结构体源码中看到,类中存有一个cache_t cache...

  • cache_t的探究

    前言 今天我们要探究的cache_t在之前的类的结构分析中看到过,在objc_class中存在一个cache_t类...

  • iOS类结构:cache_t分析

    一、cache_t 内部结构分析 1.1 在iOS类的结构分析中,我们已经分析过类(Class)的本质是一个结构体...

  • iOS底层之cache_t探索

    前言 这篇文章主要是分析cache_t流程。通过源码探索下类的cache_t主要缓存了哪些信息,又是怎么缓存的。分...

  • cache_t结构分析

    紧接着我们来分析类结构体中cache_t, 只从单词来看就能猜出来是与缓存有关. 下面我们先看cache_t的源码...

  • 七、cache_t 分析

    主要内容:cache_t的底层原理:分析cache_t缓存的内家及怎样缓存的。一、分析cache_t主要存储的是什...

  • iOS原理探索06--cache_t分析

    概要 前面文章我们分析了isa、bits,本文主要分析一下cache_t和类的关系。我们知道cache是用来缓存指...

  • iOS底层探索之方法缓存

    在分析类的时候,objc_class 结构体里面有个 cache_t cache 成员变量。 一、cache 存的...

网友评论

    本文标题:类(三)-- cache_t分析

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