iOS-类(NSObject)的方法缓存

568 阅读4分钟

上一篇文章中大概的分析了类的结构、以及类的属性与方法的存储,接下来我们分析类结构中的方法缓存:cache。

类的结构:

truct objc_class : objc_object {
    // Class ISA;
    Class superclass;
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags

。。。
}

一、cache介绍

1、cache的作用

类的方法缓存,增加方法查找效率。

2、cache_t内部结构:

struct cache_t {
    struct bucket_t *_buckets;
    mask_t _mask;
    mask_t _occupied;

public:
    struct bucket_t *buckets();
    mask_t mask();
    mask_t occupied();
    void incrementOccupied();
    void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask);
    void initializeToEmpty();

    mask_t capacity();
    bool isConstantEmptyCache();
    bool canBeFreed();

    static size_t bytesForCapacity(uint32_t cap);
    static struct bucket_t * endMarker(struct bucket_t *b, uint32_t cap);

    void expand();
    void reallocate(mask_t oldCapacity, mask_t newCapacity);
    struct bucket_t * find(cache_key_t key, id receiver);

    static void bad_cache(id receiver, SEL sel, Class isa) __attribute__((noreturn));
};
  • _buckets:bucket_t结构体的数组,bucket_t是用来存放方法的SEL内存地址和IMP的
  • _mask:数组大小 - 1,用作掩码。
  • _occupied:当前已缓存的方法数。
struct bucket_t {
    cache_key_t _key; // typedef unsigned long
    IMP _imp;
...
};
  • _key:cache_key_t 就是 unsigned long类型,用来存储SEL的内存地址。SEL应该是char类型的字符串,char强转unsigned long,其实就是SEL的内存地址。
  • _imp:方法对应的函数内存地址。

二、cache_t结构中的主要函数

1、缓存查找

bucket_t * cache_t::find(cache_key_t k, id receiver)
{
    assert(k != 0);

    bucket_t *b = buckets();
    mask_t m = mask();
    mask_t begin = cache_hash(k, m);
    mask_t i = begin;
    do {
        if (b[i].key() == 0  ||  b[i].key() == k) {
            return &b[i];
        }
    } while ((i = cache_next(i, m)) != begin);

    Class cls = (Class)((uintptr_t)this - offsetof(objc_class, cache));
    cache_t::bad_cache(receiver, (SEL)k, cls);
}

// --------------------find内部调用的cache_hash-------------------------
static inline mask_t cache_hash(cache_key_t key, mask_t mask) 
{
    return (mask_t)(key & mask);
}
// --------------------find内部调用的cache_next(arm64)-----------------
static inline mask_t cache_next(mask_t i, mask_t mask) {
    return i ? i-1 : mask;
}

分析:

  • 获取到buckets散列表与掩码mask,通过cache_hash(key & mask)得到key值对应的索引begin。

  • 将begin赋值给i,方便切换索引。

  • 进行do-while循环查找

    (i = cache_next(i, m)) != begin
    

    比如起始下标是4, 总长度是8,依次递减,当i = 0时,返回mask,则继续从总长度 = 8开始查找,直到index 再次等于 4,说明已经遍历一圈了,还是没找到,方法缓存查找结束。

    if (b[i].key() == 0  ||  b[i].key() == k)
    

    用i作为索引从散列表中取值,如果取出来的bucket_t的 key = k,则查询成功,返回该bucket_t。

    如果key = 0,说明在索引i的位置上还没有缓存过方法,同样需要返回该bucket_t,用于终止缓存查询。

  • 如果此时还没有找到key对应的bucket_t,或者是空的bucket_t,则循环结束,说明查找失败,调用bad_cache方法。

2、缓存填充插入

缓存填充插入函数中调用了查找方法,这个方法也是我们需要关注的重点

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 was not added to the cache by some other thread 
    // before we grabbed the cacheUpdateLock.
    if (cache_getImp(cls, sel)) return;

    cache_t *cache = getCache(cls);
    cache_key_t key = getKey(sel);

    // Use the cache as-is if it is less than 3/4 full
    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);
    }
    else if (newOccupied <= capacity / 4 * 3) {
        // Cache is less than 3/4 full. Use it as-is.
    }
    else {
        // 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_t *bucket = cache->find(key, receiver);
    if (bucket->key() == 0) cache->incrementOccupied();
    bucket->set(key, imp);
}
//-------------------------capacity() -----------------------------
mask_t cache_t::capacity() 
{
    return mask() ? mask()+1 : 0; 
}
  • 在确保缓存没有被其他线程添加

  • 记录对当前将要缓存的方法数mask_t newOccupied = cache->occupied() + 1;

  • 获取当前散列表的容量

  • 判断当前cache是否为只读的,也就是还未初始化,则重新分配缓存容量

  • 如果newOccupied大于容量的3/4,就要进行扩容

  • 通过find函数获取到对应的bucket_t。

  • 判断返回的bucket->key() 是否为0

    如果为0,就说明该位置上是空的,没有缓存过方法,因此需要添加一个新的缓存。

    void cache_t::incrementOccupied() 
    {
        _occupied++;
    }
    
  • 将key与imp保存在缓存中

3、缓存扩容

void cache_t::expand()
{
    cacheUpdateLock.assertLocked();
    
    uint32_t oldCapacity = capacity();
    uint32_t newCapacity = oldCapacity ? oldCapacity*2 : INIT_CACHE_SIZE;

    if ((uint32_t)(mask_t)newCapacity != newCapacity) {
        // mask overflow - can not grow further
        // fixme this wastes one bit of mask
        newCapacity = oldCapacity;
    }

    reallocate(oldCapacity, newCapacity);
}

//--------------------------------------------------------
INIT_CACHE_SIZE      = (1 << INIT_CACHE_SIZE_LOG2) // 4

当前缓存容量不存在时,开辟一个INIT_CACHE_SIZE(4)大小的缓存容量,存在则*2翻倍。

4、缓存分配

可以看到,缓存填充插入与扩容都需要用到缓存分配函数reallocate:

void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity)
{
    bool freeOld = canBeFreed();

    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);

    setBucketsAndMask(newBuckets, newCapacity - 1);
    
    if (freeOld) {
        cache_collect_free(oldBuckets, oldCapacity);
        cache_collect(false);
    }
}

用到的函数:

// 释放判断
bool cache_t::canBeFreed()
{
    return !isConstantEmptyCache();
}

bool cache_t::isConstantEmptyCache()
{
    return 
        occupied() == 0  &&  
        buckets() == emptyBucketsForCapacity(capacity(), false);
}

//---------------------------setBucketsAndMask-------------------------------
void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
{
    mega_barrier();

    _buckets = newBuckets;
    _mask = newMask;
    _occupied = 0;
}
  • 判断是否需要释放

    canBeFreed函数用来判断当前缓存是否为空,如果为空,也就没有必要释放了。

  • 根据容量newCapacity分配新的buckets

  • 为cache_t中的各个参数重新赋值,这块是指向了一个新的内存空间

  • 根据第一步的判断释放缓存

三、总结

调用方法的缓存会以一个哈希散列表bucket_t的形式保存在类结构中的cache中,cache的缓存容量不存在时,开辟一个INIT_CACHE_SIZE(4)大小的缓存容量,缓存超过容量3/4时,会进行扩容*2,开辟一个新的内存空间,并释放之前旧的缓存空间,同时保存这次的调用方法缓存。