在上一篇文章中大概的分析了类的结构、以及类的属性与方法的存储,接下来咱们分析类结构中的方法缓存: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
。。。
}
复制代码
类的方法缓存,增长方法查找效率。bash
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));
};
复制代码
struct bucket_t {
cache_key_t _key; // typedef unsigned long
IMP _imp;
...
};
复制代码
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;
}
复制代码
分析:less
获取到buckets散列表与掩码mask,经过cache_hash(key & mask)获得key值对应的索引begin。函数
将begin赋值给i,方便切换索引。post
进行do-while循环查找ui
(i = cache_next(i, m)) != begin
复制代码
好比起始下标是4, 总长度是8,依次递减,当i = 0时,返回mask,则继续从总长度 = 8开始查找,直到index 再次等于 4,说明已经遍历一圈了,仍是没找到,方法缓存查找结束。this
if (b[i].key() == 0 || b[i].key() == k)
复制代码
用i做为索引从散列表中取值,若是取出来的bucket_t的 key = k,则查询成功,返回该bucket_t。spa
若是key = 0,说明在索引i的位置上尚未缓存过方法,一样须要返回该bucket_t,用于终止缓存查询。线程
若是此时尚未找到key对应的bucket_t,或者是空的bucket_t,则循环结束,说明查找失败,调用bad_cache方法。
缓存填充插入函数中调用了查找方法,这个方法也是咱们须要关注的重点
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保存在缓存中
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翻倍。
能够看到,缓存填充插入与扩容都须要用到缓存分配函数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,开辟一个新的内存空间,并释放以前旧的缓存空间,同时保存此次的调用方法缓存。