本文主要内容
1.通过源码分析cache的缓存内容
2.cache扩容的引出
3.cache_t解析
4.cache扩容规则解析
一、通过源码分析cache的缓存内容
类对象结构体成员中有 isa、superclass、cache、bits,在前面的文章中我们了解了isa,在上一篇我们分析了bits中包含了属性、成员变量、实例方法、协议等。在这篇文章中我们将继续研究cache的结构。在上一篇文章我们知道获取类对象地址之后平移32位得到bits地址,按照这个逻辑要想得到cache的地址需要内存平移16位
找到cahche的地址,然后类型强转为cache_t的数据结构并且读取。
通过上图我们发现输出的结构体成员中并没有我们想要的信息,此时我们需要借助
objc_838.1源码查看cache_t的定义。按照之前的经验,成员变量没有找到我们需要的信息时,就需要去方法里面查找。
经过查看cache_t提供的方法,找到一个叫作insert的函数。在insert方法中注意到bucket_t *b = buckets(),而bucket_t存储的内容就是方法名和方法的实现。
void cache_t::insert(SEL sel, IMP imp, id receiver)
{
....
mask_t newOccupied = occupied() + 1;
unsigned oldCapacity = capacity(), capacity = oldCapacity;
....
bucket_t *b = buckets();
// m = bucket长度-1
mask_t m = capacity - 1;
// begin的值不会超过m
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.
do {
// 如果这个方法没有实现,就会把这个方法增加进去
if (fastpath(b[i].sel() == 0)) {
incrementOccupied();
b[i].set<Atomic, Encoded>(b, 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;
}
// 如果当前位置的self存在,并且当前sel不是要insert的sel的时候,cache_next继续往后移动
} while (fastpath((i = cache_next(i, m)) != begin));
}
// 返回bucket长度
unsigned cache_t::capacity() const
{
return mask() ? mask()+1 : 0;
}
// 已知_maybeMask = bucket_t长度-1
mask_t cache_t::mask() const
{
return _maybeMask.load(memory_order_relaxed);
}
// mask & 很大的值(value是sel强转long类型的,值会很大)最后会得到一个不超过mask的值
static inline mask_t cache_hash(SEL sel, mask_t mask)
{
uintptr_t value = (uintptr_t)sel;
#if CONFIG_USE_PREOPT_CACHES
value ^= value >> 7;
#endif
return (mask_t)(value & mask);
}
分析:
1、首先执行insert方法,通过buckets()获取到buckt_t *类型的b,找到初始位置(begin)不会超过m(bucket_t的长度-1)。
2、 执行do-while循环,循环里面:如果这个当前循环sel没有(==0),就会通过set函数将sel、imp存储进去, 退出insert函数;如果这个方法已经存在,就直接返回,退出这个insert操作;如果即有sel但是又不是要插入的sel的时候,会执行cache_next函数,继续往i+1重复当前的流程;
结论:buckets里面是存储sel和imp,insert也是在操作存储,所以cache是用来缓存方法的。
二、cache扩容的引出
在第一部分我们知道cache是用来缓存方法的。我们来看看缓存了什么方法
为LSPerson增加test方法,然后调用,此时输出cache里面的方法未找到test方法(如上图所示)。那是因为test方法未被缓存还是因为什么了?这里是因为
cache扩容了。
三、cache_t解析
在iOS底层原理之类的底层探索(上)第三部分探索## 通过内存平移得到bits数据中我们说cache(cache_t)占用16个字节。那是为什么了?
struct cache_t { // 16
private:
explicit_atomic<uintptr_t> _bucketsAndMaybeMask; // 8
union { // 联合体 8
struct { // 8
explicit_atomic<mask_t> _maybeMask; // 4
#if __LP64__
uint16_t _flags; // 2 short
#endif
uint16_t _occupied; // 2 short
};
explicit_atomic<preopt_cache_t *> _originalPreoptCache; // 8
};
//...
}
union:联合体/共用体,共用体同一时段只会存在一个属性值,共用体的内存等于最大成员变量的内存
结论:cache_t占用16个字节
四、cache扩容规则解析
1、cache扩容规则解析
在上面我们分析方法的存储是,调用方法之后,只找到了class和respondsToSelector,没有找到test方法,只是因为cache进行了扩容。查看objc源码,继续查看insert函数(具体可以查看代码的注释)。
void cache_t::insert(SEL sel, IMP imp, id receiver)
{
// ...
// Use the cache as-is if until we exceed our expected fill ratio.
mask_t newOccupied = occupied() + 1;
// capacity() = bucket_t的长度
unsigned oldCapacity = capacity(), capacity = oldCapacity;
// 判断cache是否为空(第一次进来的时候肯定是空), 在arm64架构下开辟一个长度为2的桶子,
// 在x86_64下开辟一个长度为4的桶子
if (slowpath(isConstantEmptyCache())) {
// Cache is read-only. Replace it.
// 初始值为空 capacity = 1 << INIT_CACHE_SIZE_LOG2
// CACHE_END_MARKER: 在x86_64下为1 , arm64为0
// INIT_CACHE_SIZE_LOG2:在x86_64下为2 arm64为1
// INIT_CACHE_SIZE:1<<1(arm64) 1<<2(x86_64)
// 在arm64架构下长度为2的,在x86_64架构下初始化长度为4的桶子
if (!capacity) capacity = INIT_CACHE_SIZE;
// 开辟桶子
reallocate(oldCapacity, capacity, /* freeOld */false);
}
// 在arm64架构下如果缓存的大小小于等于桶子的长度的7/8,
// 在x86_64架构下如果缓存的大小小于桶子长度的3/4则什么都不干
else if (fastpath(newOccupied + CACHE_END_MARKER <= cache_fill_ratio(capacity))) {
// Cache is less than 3/4 or 7/8 full. Use it as-is.
// cache_fill_ratio 在x84_64下为bucket_t长度的3/4
// 在arm64下为bucket_t长度的7/8
}
// 在arm64架构下,当桶子的长度小于等于8的时候,啥也不干
// 在arm架构下为 CACHE_ALLOW_FULL_UTILIZATION为:1
#if CACHE_ALLOW_FULL_UTILIZATION
// FULL_UTILIZATION_CACHE_SIZE: 1 << 3 = 8
else if (capacity <= FULL_UTILIZATION_CACHE_SIZE && newOccupied + CACHE_END_MARKER <= capacity) {
// Allow 100% cache utilization for small buckets. Use it as-is.
}
#endif
else {
capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
// MAX_CACHE_SIZE:1<<16
if (capacity > MAX_CACHE_SIZE) {
capacity = MAX_CACHE_SIZE;
}
reallocate(oldCapacity, capacity, true);
}
//...
}
slowpath::小概率执行事件
isConstantEmptyCache(): 判断cache是否为空,在arm64架构下开辟一个长度为2的桶子,在x86_t下开辟一个长度为4的桶子
void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
{
// 旧的桶子
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);
// 设置cache_t成员变量值
setBucketsAndMask(newBuckets, newCapacity - 1);
// 释放老的桶子,在第一次的时候传入false,在扩容的时候传入的是true
if (freeOld) {
collect_free(oldBuckets, oldCapacity);
}
}
cache扩容规则:
在x86_64架构下:当缓存的大小等于桶子长度的3/4的时候,进行两倍扩容
在arm_64架构下:当缓存的大小>(大于)桶子长度的7/8的时候,进行两倍扩容,当桶子的长度<=8的时候啥也不干
2、class方法和responseToSelector方法什么时候调用的?
在上面我们调用了test方法,但是通过lldb调试我们发现cache里面只找到了class方法和responseToSelector方法,找不到test方法说明cache扩容了,从这里我们看出是先调用了test方法,然后扩容。我们通过在insert函数中增加print,通过断点的方式来探索这两个方法什么时候输出的,首先在insert函数中增加print如下:
然后在调用test方法增加断点如下
通过上面的截图我们知道:当我们在lldb里面输入person.class的时候cache里面扩容,会增加class 和 respondsToSelector 方法