前言
這篇文章主要是分析cache_t
流程镀首。通過源碼探索下類的cache_t
主要緩存了哪些信息,又是怎么緩存的。
分析環(huán)境:arm64 構(gòu)架视哑,iPhone 真機(jī) 編譯環(huán)境下。
cache的存儲(chǔ)內(nèi)容
我們先來看下cache_t的源碼
struct cache_t {
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED//macOS誊涯、模擬器 -- 主要是架構(gòu)區(qū)分
// explicit_atomic 顯示原子性挡毅,目的是為了能夠 保證 增刪改查時(shí) 線程的安全性
//等價(jià)于 struct bucket_t * _buckets;
//_buckets 中放的是 sel imp
//_buckets的讀取 有提供相應(yīng)名稱的方法 buckets()
explicit_atomic<struct bucket_t *> _buckets;
explicit_atomic<mask_t> _mask;
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16 //64位真機(jī)
explicit_atomic<uintptr_t> _maskAndBuckets;//寫在一起的目的是為了優(yōu)化
mask_t _mask_unused;
//以下都是掩碼,即mask -- 類似于isa的掩碼暴构,即位域
// 掩碼省略....
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4 //非64位 真機(jī)
explicit_atomic<uintptr_t> _maskAndBuckets;
mask_t _mask_unused;
//以下都是掩碼跪呈,即mask -- 類似于isa的掩碼,即位域
// 掩碼省略....
#else
#error Unknown cache mask storage type.
#endif
#if __LP64__
uint16_t _flags;
#endif
uint16_t _occupied;
public: //對(duì)外公開可以調(diào)用的方法
static bucket_t *emptyBuckets(); // 清空buckets
struct bucket_t *buckets(); //這個(gè)方法的實(shí)現(xiàn)很簡(jiǎn)單就是_buckets對(duì)外的一個(gè)獲取函數(shù)
mask_t mask(); //獲取緩存容量_mask
mask_t occupied(); //獲取已經(jīng)占用的緩存?zhèn)€數(shù)_occupied
void incrementOccupied(); //增加緩存取逾,_occupied自++
void setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask); //這個(gè)函數(shù)是設(shè)置一個(gè)新的Buckets
void initializeToEmpty();
unsigned capacity();
bool isConstantEmptyCache();
bool canBeFreed();
}
我們?cè)賮砜聪?code>bucket_t的源碼實(shí)現(xiàn)
struct bucket_t {
private:
#if __arm64__ //真機(jī)
//explicit_atomic 是加了原子性的保護(hù)
explicit_atomic<uintptr_t> _imp;
explicit_atomic<SEL> _sel;
#else //非真機(jī)
explicit_atomic<SEL> _sel;
explicit_atomic<uintptr_t> _imp;
#endif
//方法等其他部分省略
}
通過源碼分析可知耗绿,cache
中緩存的是sel-imp
,也就是方法索引和方法實(shí)現(xiàn)砾隅。
通過例子分析cache的緩存內(nèi)容
準(zhǔn)備工作误阻,定義一個(gè)WJPerson
類,然后添加一下方法和屬性
@interface WJPerson : NSObject
{
NSString *habby;
}
@property (nonatomic, copy) NSString *name;
- (void)sayHello;
- (void)sayHowAreYou;
- (void)sayIamFine;
- (void)sayThanksYou;
- (void)sayAndYou;
+ (void)sayGoodbye;
@end
@implementation WJPerson
- (void)sayHello{
NSLog(@"%s",__func__);
}
- (void)sayHowAreYou{
NSLog(@"%s",__func__);
}
- (void)sayIamFine{
NSLog(@"%s",__func__);
}
- (void)sayThanksYou{
NSLog(@"%s",__func__);
}
- (void)sayAndYou{
NSLog(@"%s",__func__);
}
+ (void)sayGoodbye{
NSLog(@"%s",__func__);
}
@end
然后在main.m
中創(chuàng)建一個(gè)對(duì)象晴埂,并調(diào)用方法打好斷點(diǎn)究反,然后運(yùn)行啟動(dòng)。
sel
和imp
了呢琅锻。有的同學(xué)會(huì)說是init
卦停,到底是不是呢,接下來我們驗(yàn)證一下浅浮。init
方法沫浆。接下來我們走的第二個(gè)斷點(diǎn),看下接下來的數(shù)據(jù)滚秩。我們?cè)賵?zhí)行下上面的步驟
init
方法嗎攀痊。是不是不在第一個(gè)位置啊桐腌,我們?cè)倏匆幌?code>buckets中的其他元素。lldb
這樣找太麻煩了,有沒有一種更簡(jiǎn)單的方式棘街。接下來我們通過更簡(jiǎn)單的方式來看一下蟆盐。
typedef uint32_t mask_t; // x86_64 & arm64 asm are less efficient with 16-bits
struct wj_bucket_t {
SEL _sel;
IMP _imp;
};
struct wj_cache_t {
struct wj_bucket_t * _buckets;
mask_t _mask;
uint16_t _flags;
uint16_t _occupied;
};
struct wj_class_data_bits_t {
uintptr_t bits;
};
struct wj_objc_class {
Class ISA;
Class superclass;
struct wj_cache_t cache; // formerly cache pointer and vtable
struct wj_class_data_bits_t bits; // class_rw_t * plus custom rr/alloc flags
};
int main(int argc, const char * argv[]) {
@autoreleasepool {
WJPerson *person = [[WJPerson alloc] init];
Class personClass = [person class];
[person sayHello];
// [person sayHowAreYou];
// [person sayIamFine];
// [person sayThanksYou];
// [person sayAndYou];
[personClass sayGoodbye];
struct wj_objc_class *wj_pClass = (__bridge struct wj_objc_class *)(personClass);
NSLog(@"%hu - %u",wj_pClass->cache._occupied,wj_pClass->cache._mask);
for (mask_t i = 0; i<wj_pClass->cache._mask; i++) {
// 打印獲取的 bucket
struct wj_bucket_t bucket = wj_pClass->cache._buckets[i];
NSLog(@"%@ - %p",NSStringFromSelector(bucket._sel),bucket._imp);
}
NSLog(@"%@", personClass);
}
return 0;
}
我們把cache_t
相關(guān)的源碼拷貝過來承边,加工成我們自己的wj_cache_t
,然后通過我們自己的wj_cache_t
看一下緩存結(jié)果石挂。
首先我們只調(diào)用其中一個(gè)方法博助,看下打印結(jié)果
-
occupied
和mask
是什么,又是怎么變化的呢拯腮。 - 為什么會(huì)出現(xiàn)有的方法沒有打印的情況呢窖式。
- 為什么
buckets
中方法的順序和我們的調(diào)用順序不一致呢。
接下來我們分析下cache_t
的源碼
cache_t源碼分析
cache_t
結(jié)構(gòu)动壤,發(fā)現(xiàn)public
方法處脖镀,有incrementOccupied
函數(shù)和setBucketsAndMask
函數(shù)。進(jìn)入
incrementOccupied
發(fā)現(xiàn)只是執(zhí)行了_occupied++
狼电。
void cache_t::incrementOccupied()
{
_occupied++;
}
進(jìn)入setBucketsAndMask
發(fā)現(xiàn)每次都是重新設(shè)置_buckets
和_mask
蜒灰,并且把_occupied
設(shè)置為0
void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
{
// objc_msgSend uses mask and buckets with no locks.
// It is safe for objc_msgSend to see new buckets but old mask.
// (It will get a cache miss but not overrun the buckets' bounds).
// It is unsafe for objc_msgSend to see old buckets and new mask.
// Therefore we write new buckets, wait a lot, then write new mask.
// objc_msgSend reads mask first, then buckets.
#ifdef __arm__
// ensure other threads see buckets contents before buckets pointer
mega_barrier();
_buckets.store(newBuckets, memory_order::memory_order_relaxed);
// ensure other threads see new buckets before new mask
mega_barrier();
_mask.store(newMask, memory_order::memory_order_relaxed);
_occupied = 0;
#elif __x86_64__ || i386
// ensure other threads see buckets contents before buckets pointer
// 存儲(chǔ)新的buckets
_buckets.store(newBuckets, memory_order::memory_order_release);
// ensure other threads see new buckets before new mask
// 存儲(chǔ)新的mask
_mask.store(newMask, memory_order::memory_order_release);
// occupied占用z設(shè)為0
_occupied = 0;
#else
#error Don't know how to do setBucketsAndMask on this architecture.
#endif
}
通過這兩個(gè)方法的實(shí)現(xiàn),我們發(fā)現(xiàn)incrementOccupied
是執(zhí)行計(jì)數(shù)加一操作肩碟,那么我們判斷調(diào)用incrementOccupied
方法的地方應(yīng)該就是核心業(yè)務(wù)處理的過程强窖,所以我們搜索incrementOccupied
去看看哪里調(diào)用了它。發(fā)現(xiàn)只有cache_t::insert
使用到了它削祈。那我們?cè)僬蚁?code>cache->insert又在哪里被使用了呢翅溺,發(fā)現(xiàn)只有一處cache_fill
調(diào)用了cache->insert
,然后我們?cè)偻险宜枰郑l(fā)現(xiàn)找不到調(diào)用cache_fill
的地方咙崎,說明這里又是經(jīng)過編譯器做了處理,所以我們今天就只討論cache_fill —>insert
里的操作吨拍。
我們先來看下cache_fill
的源碼
void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
{
runtimeLock.assertLocked(); // runtime鎖 assert斷言
#if !DEBUG_TASK_THREADS
// Never cache before +initialize is done
if (cls->isInitialized()) {
cache_t *cache = getCache(cls);//獲取當(dāng)前的cache緩存池
#if CONFIG_USE_CACHE_LOCK
mutex_locker_t lock(cacheUpdateLock);
#endif
cache->insert(cls, sel, imp, receiver);//向緩存池中插入信息
}
#else
_collecting_in_critical();
#endif
}
然后我們看下cache_t::insert
的源碼
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());
// 原occupied計(jì)數(shù)+1
mask_t newOccupied = occupied() + 1;
// 進(jìn)入查看: return mask() ? mask()+1 : 0;
// 就是當(dāng)前mask有值就+1褪猛,否則設(shè)置初始值0
unsigned oldCapacity = capacity(), capacity = oldCapacity;
// 當(dāng)前緩存是否為空
if (slowpath(isConstantEmptyCache())) {
// Cache is read-only. Replace it.
// 如果為空,就給空間設(shè)置初始值4
// (進(jìn)入INIT_CACHE_SIZE查看羹饰,可以發(fā)現(xiàn)就是1<<2伊滋,就是二進(jìn)制100,十進(jìn)制為4)
if (!capacity) capacity = INIT_CACHE_SIZE;
// 創(chuàng)建新空間(第三個(gè)入?yún)閒alse队秩,表示不需要釋放舊空間)
reallocate(oldCapacity, capacity, /* freeOld */false);
}
// CACHE_END_MARKER 就是 1
// 如果當(dāng)前計(jì)數(shù)+1 < 空間的 3/4笑旺。 就不用處理
// 表示空間夠用。 不需要空間擴(kuò)容
else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
// Cache is less than 3/4 full. Use it as-is.
}
// 如果計(jì)數(shù)大于3/4馍资, 就需要進(jìn)行擴(kuò)容操作
else {
// 如果空間存在筒主,就2倍擴(kuò)容。 如果不存在,就設(shè)為初始值4
capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
// 防止超出最大空間值(2^16 - 1)
if (capacity > MAX_CACHE_SIZE) {
capacity = MAX_CACHE_SIZE;
}
// 創(chuàng)建新空間(第三個(gè)入?yún)閠rue乌妙,表示需要釋放舊空間)
reallocate(oldCapacity, capacity, true);
}
// 讀取現(xiàn)在的buckets數(shù)組
bucket_t *b = buckets();
// 新的mask值(當(dāng)前空間最大存儲(chǔ)大小)
mask_t m = capacity - 1;
// 使用hash計(jì)算當(dāng)前函數(shù)的位置(內(nèi)部就是sel & m使兔, 就是取余操作,保障begin值在m當(dāng)前可用空間內(nèi))
mask_t begin = cache_hash(sel, m);
mask_t i = begin;
do {
// 如果當(dāng)前位置為空(空間位置沒被占用)
if (fastpath(b[i].sel() == 0)) {
// Occupied計(jì)數(shù)+1
incrementOccupied();
// 將sle和imp與cls關(guān)聯(lián)起來并寫入內(nèi)存中
b[i].set<Atomic, Encoded>(sel, imp, cls);
return;
}
// 如果當(dāng)前位置有值(位置被占用)
if (b[i].sel() == sel) {
// The entry was added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
// 直接返回
return;
}
// 如果位置有值冠胯,再次使用哈希算法找下一個(gè)空位置去寫入
// 需要注意的是火诸,cache_next內(nèi)部有分支:
// 如果是arm64真機(jī)環(huán)境: 從最大空間位置開始,依次-1往回找空位
// 如果是arm舊版真機(jī)荠察、x86_64電腦置蜀、i386模擬器: 從當(dāng)前位置開始,依次+1往后找空位悉盆。不能超過最大空間盯荤。
// 因?yàn)楫?dāng)前空間是沒超出mask最大空間的,所以一定有空位置可以放置的焕盟。
} while (fastpath((i = cache_next(i, m)) != begin));
// 各種錯(cuò)誤處理
cache_t::bad_cache(receiver, (SEL)sel, cls);
}
我們?cè)倏聪?code>reallocate方法的實(shí)現(xiàn)秋秤,看下他是怎么對(duì)內(nèi)存空間進(jìn)行操作的
bucket_t *allocateBuckets(mask_t newCapacity)
{
// 創(chuàng)建1個(gè)bucket
bucket_t *newBuckets = (bucket_t *)
calloc(cache_t::bytesForCapacity(newCapacity), 1);
// 將創(chuàng)建的bucket放到當(dāng)前空間的最尾部,標(biāo)記數(shù)組的結(jié)束
bucket_t *end = cache_t::endMarker(newBuckets, newCapacity);
#if __arm__
// End marker's sel is 1 and imp points BEFORE the first bucket.
// This saves an instruction in objc_msgSend.
end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)(newBuckets - 1), nil);
#else
// 將結(jié)束標(biāo)記為sel為1脚翘,imp為這個(gè)buckets
end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)newBuckets, nil);
#endif
// 只是打印記錄
if (PrintCaches) recordNewCache(newCapacity);
// 返回這個(gè)bucket
return newBuckets;
}
我們看下allocateBuckets
開辟新空間的操作
bucket_t *allocateBuckets(mask_t newCapacity)
{
// 創(chuàng)建1個(gè)bucket
bucket_t *newBuckets = (bucket_t *)
calloc(cache_t::bytesForCapacity(newCapacity), 1);
// 將創(chuàng)建的bucket放到當(dāng)前空間的最尾部灼卢,標(biāo)記數(shù)組的結(jié)束
bucket_t *end = cache_t::endMarker(newBuckets, newCapacity);
#if __arm__
// End marker's sel is 1 and imp points BEFORE the first bucket.
// This saves an instruction in objc_msgSend.
end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)(newBuckets - 1), nil);
#else
// 將結(jié)束標(biāo)記為sel為1,imp為這個(gè)buckets
end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)newBuckets, nil);
#endif
// 只是打印記錄
if (PrintCaches) recordNewCache(newCapacity);
// 返回這個(gè)bucket
return newBuckets;
}
最后我們看下cache_collect_free
是怎么釋放內(nèi)存空間的
static void cache_collect_free(bucket_t *data, mask_t capacity)
{
#if CONFIG_USE_CACHE_LOCK
cacheUpdateLock.assertLocked();
#else
runtimeLock.assertLocked();
#endif
if (PrintCaches) recordDeadCache(capacity);
// 垃圾房: 開辟空間 (如果首次来农,就開辟初始空間鞋真,如果不是,就空間*2進(jìn)行拓展)
_garbage_make_room ();
// 將當(dāng)前擴(kuò)容后的capacity加入垃圾房的尺寸中沃于,便于后續(xù)釋放涩咖。
garbage_byte_size += cache_t::bytesForCapacity(capacity);
// 將當(dāng)前新數(shù)據(jù)data存放到 garbage_count 后面 這樣可以釋放前面的,而保留后面的新值
garbage_refs[garbage_count++] = data;
// 不記錄之前的緩存 = 【清空之前的緩存】繁莹。
cache_collect(false);
}
最后我們可以總結(jié)一個(gè)流程圖
經(jīng)過我們的分析檩互,相信你對(duì)前面的疑問已經(jīng)有了答案。
1.
occupied
和 mask
是什么咨演,又是怎么變化的呢闸昨。函數(shù)寫入
cache
緩存時(shí),occupied
會(huì)加1雪标,mask
記錄當(dāng)前cache
最大可存儲(chǔ)空間零院。當(dāng)
inset
緩存的操作,觸發(fā)空間使用率超過3/4
村刨,空間2倍擴(kuò)容
時(shí),mask
記錄新空間的最大可存儲(chǔ)大小撰茎,因?yàn)?code>舊空間被釋放嵌牺,之前cache
的所有內(nèi)容都被垃圾房清空了,所以occupied
重置為0。從新開始計(jì)數(shù)2. 為什么會(huì)出現(xiàn)有的方法沒有打印的情況呢逆粹。
因?yàn)橛|發(fā)空間擴(kuò)容時(shí)募疮,
舊空間被釋放
,所以cache
中的舊值都被清空僻弹。 新值插入新cache
空間阿浓。3. 為什么
buckets
中方法的順序和我們的調(diào)用順序不一致呢。插入操作是使用的
hash
算法蹋绽。插入位置是經(jīng)過取余計(jì)算的芭毙。且如果插入位置已經(jīng)有值,就會(huì)不停的后移1位卸耘,直到找到空位置完成插入位置退敦。