cache_t作用
用来缓存通过对象调用过的方法。当再次调用的时候,能够快速的通过sel
找到方法imp
cache_t结构
相关源码如下:
#if defined(__arm64__) && __LP64__
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_HIGH_16
#elif defined(__arm64__) && !__LP64__
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_LOW_4
#else
#define CACHE_MASK_STORAGE CACHE_MASK_STORAGE_OUTLINED
#endif
struct cache_t {
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
explicit_atomic<struct bucket_t *> _buckets;
explicit_atomic<mask_t> _mask;
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
// How much the mask is shifted by.
static constexpr uintptr_t maskShift = 48;
// Additional bits after the mask which must be zero. msgSend
// takes advantage of these additional bits to construct the value
// `mask << 4` from `_maskAndBuckets` in a single instruction.
static constexpr uintptr_t maskZeroBits = 4;
// The largest mask value we can store.
static constexpr uintptr_t maxMask = ((uintptr_t)1 << (64 - maskShift)) - 1;
// The mask applied to `_maskAndBuckets` to retrieve the buckets pointer.
static constexpr uintptr_t bucketsMask = ((uintptr_t)1 << (maskShift - maskZeroBits)) - 1;
// Ensure we have enough bits for the buckets pointer.
static_assert(bucketsMask >= MACH_VM_MAX_ADDRESS, "Bucket field doesn't have enough bits for arbitrary pointers.");
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
// _maskAndBuckets stores the mask shift in the low 4 bits, and
// the buckets pointer in the remainder of the value. The mask
// shift is the value where (0xffff >> shift) produces the correct
// mask. This is equal to 16 - log2(cache_size).
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
static constexpr uintptr_t maskBits = 4;
static constexpr uintptr_t maskMask = (1 << maskBits) - 1;
static constexpr uintptr_t bucketsMask = ~maskMask;
#else
#error Unknown cache mask storage type.
#endif
#if __LP64__
uint16_t _flags;
#endif
uint16_t _occupied;
//省略后面代码
......
}
struct bucket_t {
private:
// IMP-first is better for arm64e ptrauth and no worse for arm64.
// SEL-first is better for armv7* and i386 and x86_64.
#if __arm64__
explicit_atomic<uintptr_t> _imp;
explicit_atomic<SEL> _sel;
#else
explicit_atomic<SEL> _sel;
explicit_atomic<uintptr_t> _imp;
#endif
//省略后面代码
......
}
-
结构体cache_t中进行了编译条件判断:
- CACHE_MASK_STORAGE_OUTLINED:其它情况(本文主要研究方向,另外两种同理,但是稍微复杂)
- CACHE_MASK_STORAGE_HIGH_16:代表arm64平台并且是64位设备
- CACHE_MASK_STORAGE_LOW_4:代表arm64平台、非64位设备
-
_buckets:
struct bucket_t
类型,数组形式存储sel和imp。(注意,不同平台下,sel和imp顺序不一样。原因注释中有解释,就是一种针对不同平台的优化。) -
_mask:
mask_t
类型。也是针对不同平台的定义的别名,源码如下:#if __LP64__ typedef uint32_t mask_t; // x86_64 & arm64 asm are less efficient with 16-bits #else typedef uint16_t mask_t;
作用是记录当前已开辟的内存空间可用的最大值。
-
_flags:uint16_t类型,内部使用的标志位。
-
_occupied:uint16_t类型,表示缓存中已经占用数。如果缓存了一个方法,_occupied就设置为1。两个方法,则为2。
lldb调试
Person *p = [Person alloc];
Class pClass = [Person class];
[p sayHello];
[p sayCode];
NSLog(@"%@",pClass);

- 打印类的内存地址
-
cache_t cache
在结构体中第三个位置,前两个是指针类型,分别是isa
和superclass
,所以内存便宜是16字节,转换16进制是10。因此在原地址上进行+10操作。 - 得到
cache_t *
类型的$1
,调用buckets()
函数得到bucket_t *
类型的$2
- 调用
sel()
和imp(pClass)
函数,可以打印出缓存的方法的sel
和imp
- 通过指针偏移打印后面的缓存方法信息。
- 通过打印
$1
中的值,能够看到目前_occupied
的值是2,说明目前的缓存空间占用了2个位置,就是示例中调用过的两个方法被缓存了。
方法缓存的插入逻辑
对象调用方法会间接调用源码中的下面函数
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<Atomic, Encoded>(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);
}
源码的逻辑:
- 首先进行cache是否为空的状态
if (slowpath(isConstantEmptyCache()))
,然后对容器大小进行初始值赋值capacity = INIT_CACHE_SIZE
,并且调用reallocate
函数进行内存空间开辟 - 然后进行容器大小的3/4判断,如果超过3/4,进行二倍扩容,调用
reallocate
函数开辟内存空间 - 保证空间够用后,最后进行保存被调用方法的sel和imp:
- 此处对sel进行哈希计算(哈希函数:sel转换成无符号的长整形 & 当前的可用空间大小mask),求出位置
- 进行do-while循环,看看这个位置有没有值:
- 没有值就插入
- 有值进行sel比较,相等就直接返回,说明此方法已经缓存过;
- 如果位置上有值,并且sel不相等,就对位置+1后 & 总空间大小mask,进行再次哈希(哈希冲突的开放地址法)。)。
网友评论