iOS方法缓存cache_t流程-海浪宝宝

先放一份流程图:

cache流程图.png

从上帝视角,我们知道缓存方法的入口是cache_fill_nolock,所以我们先找到cache_fill_nolock方法,查看他的实现,然后我们从上往下分析

方法缓存逻辑

static void cache_fill_nolock(Class cls, SEL sel, IMP imp, id receiver)
{
    cacheUpdateLock.assertLocked();

    // Never cache before +initialize is done
    if (!cls->isInitialized()) return;

    // Make sure the entry wasn't added to the cache by some other thread 
    // before we grabbed the cacheUpdateLock.
    //如果能取到方法指针,直接返回,看不到源码
    if (cache_getImp(cls, sel)) return;
    //取到缓存池
    cache_t *cache = getCache(cls);
    //将方法强转成long类型,当做key使用,这里我们可以看到缓存池是将SEL转成一个long类型来当做key使用
    cache_key_t key = getKey(sel);

    // Use the cache as-is if it is less than 3/4 full
    //取到当前缓存池的缓存方法数并+1
    mask_t newOccupied = cache->occupied() + 1;
    //取到缓存池的总容量
    mask_t capacity = cache->capacity();
    //缓存池如果是空,则创建一个缓存池
    if (cache->isConstantEmptyCache()) {
        // Cache is read-only. Replace it.
        cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);
    }//再加一个缓存,如果缓存池的缓存的方法数小于缓存池容量的4/3则不管,如果大于则扩容
    else if (newOccupied <= capacity / 4 * 3) {
        // Cache is less than 3/4 full. Use it as-is.
    }
    else {//如果缓存的方法大于容量的4/3,则扩容,扩容成现有缓存池总容量的2倍
        // Cache is too full. Expand it.
        cache->expand();
    }

    // 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.
    //
    //从缓存池中取出该方法对应的bucket
    bucket_t *bucket = cache->find(key, receiver);
    //如果取到的bucket的key为0说明没从缓存池中取到改方法,那么就将缓存池已缓存的数量+1
    if (bucket->key() == 0) cache->incrementOccupied();
    //将执行的方法缓存的缓存池中
    bucket->set(key, imp);
}

结论:

里面我们可以看到苹果的缓存逻辑是当新方法进来之前判断加入后缓存的值是否大于总容量的4/3,如果大于则将缓存池扩容成老缓存池的二倍,这个缓存思想比较好,不会随便建立大的缓存池,也不会导致不够用,

扩容方法

//扩容方法,将容量扩充到原来的2倍,如果为空的话则默认给个4
void cache_t::expand()
{
    cacheUpdateLock.assertLocked();
    
    uint32_t oldCapacity = capacity();
    uint32_t newCapacity = oldCapacity ? oldCapacity*2 : INIT_CACHE_SIZE;
    //新的容量值强转成uint32_t,和原来的不相等就用老的容量值?
    if ((uint32_t)(mask_t)newCapacity != newCapacity) {
        // mask overflow - can't grow further
        // fixme this wastes one bit of mask
        newCapacity = oldCapacity;
    }
    //创建新的容量池,创建完成后会将原来缓存的方法清除掉
    reallocate(oldCapacity, newCapacity);
}

开辟缓存池

开辟缓存池方法

void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity)
{
    //如果缓存池容量为0,且缓存的方法为空,则不能清空
    bool freeOld = canBeFreed();
    //q取到老的缓存池
    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);
    //初始化缓存池,缓存池的可缓存数比缓存池的r总容量要小1
    setBucketsAndMask(newBuckets, newCapacity - 1);
    //释放老的缓存池
    if (freeOld) {
        cache_collect_free(oldBuckets, oldCapacity);
        cache_collect(false);
    }
}

结论:

开辟方法不仅仅是在新建容量池时候用,而且扩容时候也用这个方法,最后一句就是在建立新的容量池后,苹果会将老的容量池释放掉,这个需要注意

初始化缓存池方法:


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.

    // ensure other threads see buckets contents before buckets pointer
    mega_barrier();

    _buckets = newBuckets;
    
    // ensure other threads see new buckets before new mask
    mega_barrier();
    
    _mask = newMask;
    _occupied = 0;
}

作者:海浪宝宝
链接:https://juejin.cn/post/6844904030804639752
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(iOS方法缓存cache_t流程-海浪宝宝)