緊接著我們來(lái)分析類(lèi)結(jié)構(gòu)體中cache_t, 只從單詞來(lái)看就能猜出來(lái)是與緩存有關(guān). 下面我們先看cache_t的源碼:
struct cache_t {
#if 1 // Mac
struct bucket_t * _buckets;
mask_t _mask;
#elif 1 // 真機(jī) (盡量用真機(jī)調(diào)試, 因?yàn)檎鏅C(jī)更貼近日常使用)
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;
#endif
uint16_t _flags; // 標(biāo)志位
uint16_t _occupied; // 被占用的
public:
static bucket_t *emptyBuckets();
struct bucket_t *buckets();
mask_t mask();
mask_t occupied();
void incrementOccupied();
void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask);
void initializeToEmpty();
unsigned capacity();
bool isConstantEmptyCache();
bool canBeFreed();
void reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld);
void insert(Class cls, SEL sel, IMP imp, id receiver);
};
在進(jìn)行結(jié)構(gòu)分析時(shí), 我們先寫(xiě)了一個(gè)例子來(lái)分析cache_t的結(jié)構(gòu). 具體例子如下:
//LGPerson.h文件
@interface LGPerson : NSObject
@property (nonatomic, copy) NSString *lgName;
@property (nonatomic, strong) NSString *nickName;
- (void)say1;
- (void)say2;
- (void)say3;
- (void)say4;
//LGPerson.m文件
#import "LGPerson.h"
@implementation LGPerson
- (void)say1{
NSLog(@"LGPerson say : %s",__func__);
}
- (void)say2{
NSLog(@"LGPerson say : %s",__func__);
}
- (void)say3{
NSLog(@"LGPerson say : %s",__func__);
}
- (void)say4{
NSLog(@"LGPerson say : %s",__func__);
}
@end
具體調(diào)用以及打印結(jié)果, 見(jiàn)下方代碼:
#import <Foundation/Foundation.h>
#import "LGPerson.h"
#import <objc/runtime.h>
typedef uint32_t mask_t; // x86_64 & arm64 asm are less efficient with 16-bits
struct lg_bucket_t {
SEL _sel;
IMP _imp;
};
struct lg_cache_t {
struct lg_bucket_t * _buckets;
mask_t _mask;
uint16_t _flags;
uint16_t _occupied;
};
struct lg_class_data_bits_t {
uintptr_t bits;
};
struct lg_objc_class {
Class ISA;
Class superclass;
struct lg_cache_t cache; // formerly cache pointer and vtable
struct lg_class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
};
int main(int argc, const char * argv[]) {
@autoreleasepool {
LGPerson *p = [LGPerson alloc];
Class pClass = [LGPerson class]; // objc_clas
[p say1];
[p say2];
// [p say3];
// [p say4];
struct lg_objc_class *lg_pClass = (__bridge struct lg_objc_class *)(pClass);
NSLog(@"%hu - %u",lg_pClass->cache._occupied,lg_pClass->cache._mask);
for (mask_t i = 0; i<lg_pClass->cache._mask; i++) {
// 打印獲取的 bucket
struct lg_bucket_t bucket = lg_pClass->cache._buckets[i];
NSLog(@"%@ - %p",NSStringFromSelector(bucket._sel),bucket._imp);
}
NSLog(@"Hello, World!");
}
return 0;
}
//當(dāng)屏蔽 [p say3]; [p say4]; 方法時(shí)的打印結(jié)果:
2020-09-17 21:23:31.259617+0800 003-cache_t脫離源碼環(huán)境分析[3956:50598] LGPerson say : -[LGPerson say1]
2020-09-17 21:23:31.259990+0800 003-cache_t脫離源碼環(huán)境分析[3956:50598] LGPerson say : -[LGPerson say2]
2020-09-17 21:23:31.260029+0800 003-cache_t脫離源碼環(huán)境分析[3956:50598] 2 - 3
2020-09-17 21:23:35.029171+0800 003-cache_t脫離源碼環(huán)境分析[3956:50598] say1 - 0x2828
2020-09-17 21:23:35.029352+0800 003-cache_t脫離源碼環(huán)境分析[3956:50598] say2 - 0x2818
2020-09-17 21:23:35.029409+0800 003-cache_t脫離源碼環(huán)境分析[3956:50598] (null) - 0x0
//當(dāng)打開(kāi)屏幕 [p say3]; [p say4]; 的打印結(jié)果為:
2020-09-17 21:37:09.315693+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] LGPerson say : -[LGPerson say1]
2020-09-17 21:37:09.315964+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] LGPerson say : -[LGPerson say2]
2020-09-17 21:37:09.316001+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] LGPerson say : -[LGPerson say3]
2020-09-17 21:37:09.316076+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] LGPerson say : -[LGPerson say4]
2020-09-17 21:37:09.316099+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] 2 - 7
2020-09-17 21:37:09.316196+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] say4 - 0x29a8
2020-09-17 21:37:09.316217+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] (null) - 0x0
2020-09-17 21:37:09.316283+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] say3 - 0x29d8
2020-09-17 21:37:09.316315+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] (null) - 0x0
2020-09-17 21:37:09.316330+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] (null) - 0x0
2020-09-17 21:37:09.316366+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] (null) - 0x0
2020-09-17 21:37:09.316382+0800 003-cache_t脫離源碼環(huán)境分析[4296:55622] (null) - 0x0
我們先拋出問(wèn)題:以及最終的得出的結(jié)論
// _occupied _mask 是什么 cup - 1
// 會(huì)變化 2-3 -> 2-7 (說(shuō)明有做擴(kuò)容操作)
// bucket 會(huì)有丟失 重新申請(qǐng)
// 順序有點(diǎn)問(wèn)題 哈希
// 當(dāng)打開(kāi)屏蔽方法后, 沒(méi)有打印出 say1 say2, 證明有做刷新釋放操作
然后我們從cache_t的源碼來(lái)分析: 每當(dāng)對(duì)象調(diào)用一個(gè)方法時(shí), 如果在cache里面沒(méi)有找到, 就會(huì)insert一條緩存:
void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)
{
// Use the cache as-is if it is less than 3/4 full
mask_t newOccupied = occupied() + 1;
unsigned oldCapacity = capacity(), capacity = oldCapacity;
// 1. 如果Cache 是空的話,會(huì)初始化一個(gè) 4 個(gè)字節(jié)的空間
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)) {
// Cache is less than 3/4 full. Use it as-is.
// 2. newOccupied + CACHE_END_MARKER <= capacity / 4 * 3 ,直接插入
}
else {
// 3. 否則會(huì)擴(kuò)容, 擴(kuò)容為原空間的 2倍大小
capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
if (capacity > MAX_CACHE_SIZE) {
capacity = MAX_CACHE_SIZE;
}
reallocate(oldCapacity, capacity, true); // // 重新分配空間 存儲(chǔ)新的數(shù)據(jù),抹除已有緩存
}
// 4. 初始化一個(gè)指針數(shù)組
bucket_t *b = buckets();
// 5. 設(shè)置掩碼為 capacity - 1
mask_t m = capacity - 1;
// 6. 根據(jù)sel 計(jì)算 hash 值
mask_t begin = cache_hash(sel, m);
mask_t i = begin;
/*
* 掃描第一個(gè)未使用的插槽,并且插入
*/
// 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 {
// 7. 當(dāng)前 插槽 取到 的sel 地址為0, 那么插入新的值
if (fastpath(b[i].sel() == 0)) {
// 8. 增加占用字段并且插入
incrementOccupied();
b[i].set<Atomic, Encoded>(sel, imp, cls);
return;
}
// 8. 多線程做的判斷
if (b[i].sel() == sel) { // 如果找到需要緩存的方法,什么都不做,并退出循環(huán)
// The entry was added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
return;
}
// 9. 如果當(dāng)前位置已有值,那么就找下一個(gè)位置 判斷不等于初始下標(biāo)值 begin 是為了將散列表中的數(shù)據(jù)全部遍歷結(jié)束,而cache_next( ) 是為了解決哈希沖突而進(jìn)行的二次哈希.
} while (fastpath((i = cache_next(i, m)) != begin));
}
// 10. hash 算法, 保證不會(huì)越界
static inline mask_t cache_hash(SEL sel, mask_t mask)
{
return (mask_t)(uintptr_t)sel & mask;
}

cache_t緩存流程圖
總結(jié)一下cache_t的結(jié)構(gòu):

cache_t結(jié)構(gòu)
- _buckets :是一個(gè)散列表,用來(lái)存儲(chǔ) 緩存方法的 sel 和 imp.
- _mask : 有2個(gè)作用,1: 作為當(dāng)前可存儲(chǔ)的最大容量;2: 作為掩碼,取已緩存方法在 _buckets 中的下標(biāo).
- _occupied : _buckets 中 已緩存的方法數(shù)量.