OC底层06:Cache_t分析

之前分析了objc_class中的class_data_bits_tisa,还剩下cache_t,今天来进行分析一下

结构


总结下来主要有4个参数:

bucket_t * _buckets; //缓存方法的散列表 explicit_atomic是原子性
mask_t _mask; //散列表的长度
uint16_t _flags;//标志位
uint16_t _occupied;//占用的空间

验证

1.

//创建Person类
@interface Person : NSObject
- (void)method1;
- (void)method2;
- (void)method3;
- (void)method4;
@end

//调用
Person *p = [Person alloc];
Class pClass = [Person class];        
[p method1];
[p method2];
[p method3];
[p method4];

2. 先将断点断在[p method1];处,lldb调试


ps:如果不使用pClass,使用p.class,会调用class方法,并将class写入cache中,这样查看的mask与occupied不为0

3.点击step over执行一步,调试


此时,散列表长度变成了3,占用为1,查看缓存可以看到:

这里可以看到method1已经在缓存中了。

注意点

1.cache_t结构体中,buckets的定义为explicit_atomic _buckets,你如果通过.buckets->buckets 会发现根本无法获取到buckets,仔细阅读源码会发现cache_t中提供了struct bucket_t *buckets()用于获取buckets。所以如图,通过.buckets()获取,sel同理。
2.buckets是存在散列表中,如果有多个buckets可以通过指针偏移获取,再执行[p method2]:

3.继续执行[p method3],会发现mask变成了7,occupied变成了1


需要了解为什么会这样变化,我们需要从cache_t的插入源码入手。

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;
    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(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);
}
  1. 当缓存为空时,会初始化缓存
if (slowpath(isConstantEmptyCache())) {
        // Cache is read-only. Replace it.
        if (!capacity) capacity = INIT_CACHE_SIZE;
        reallocate(oldCapacity, capacity, /* freeOld */false);
    }

2.当缓存不为空,且不大于总大小的3/4减1时,不进行任何操作(#define CACHE_END_MARKER 1)

    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.
    }

3.当总大小不够时,会进行扩容

    else {
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;  // 扩容两倍 4
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
        reallocate(oldCapacity, capacity, true);  // 内存 库容完毕
    }

如此可以找到原因:第一次申请空间为4,maskcapacity-1=3,method1method2插入时,满足newOccupied + CACHE_END_MARKER <= capacity / 4 * 3,而当method3插入时,newOccupied变为3,3+1>4/4*3所以要进行扩容,原有缓存被舍去,只插入了method3,故occupied变成了1,mask变成了7

其他

cache的插入时乱序的。

    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(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));
  1. cache的插入不是顺序插入,是先做一次哈希计算,由这个值开始mask_t begin = cache_hash(sel, m)

2.cache当哈希计算出的位置中值为空时,插入。

 if (fastpath(b[i].sel() == 0)) {
            incrementOccupied();
            b[i].set(sel, imp, cls);
            return;
        }

3.哈希计算的位置值相同时跳过,不再插入。

        if (b[i].sel() == sel) {
            // The entry was added to the cache by some other thread
            // before we grabbed the cacheUpdateLock.
            return;
        }

4.继续哈希,直到找到合适的位置插入while (fastpath((i = cache_next(i, m)) != begin))

你可能感兴趣的:(OC底层06:Cache_t分析)