OC底層06:Cache_t分析

之前分析了objc_class中的class_data_bits_tisa,還剩下cache_t,今天來(lái)進(jìn)行分析一下

結(jié)構(gòu)


總結(jié)下來(lái)主要有4個(gè)參數(shù):

bucket_t * _buckets; //緩存方法的散列表 explicit_atomic是原子性
mask_t _mask; //散列表的長(zhǎng)度
uint16_t _flags;//標(biāo)志位
uint16_t _occupied;//占用的空間

驗(yàn)證

1.

//創(chuàng)建Person類(lèi)
@interface Person : NSObject
- (void)method1;
- (void)method2;
- (void)method3;
- (void)method4;
@end

//調(diào)用
Person *p = [Person alloc];
Class pClass = [Person class];        
[p method1];
[p method2];
[p method3];
[p method4];

2. 先將斷點(diǎn)斷在[p method1];處,lldb調(diào)試


ps:如果不使用pClass,使用p.class,會(huì)調(diào)用class方法,并將class寫(xiě)入cache中,這樣查看的mask與occupied不為0

3.點(diǎn)擊step over執(zhí)行一步,調(diào)試


此時(shí),散列表長(zhǎng)度變成了3,占用為1,查看緩存可以看到:

這里可以看到method1已經(jīng)在緩存中了。

注意點(diǎn)

1.cache_t結(jié)構(gòu)體中,buckets的定義為explicit_atomic<struct bucket_t *> _buckets,你如果通過(guò).buckets->buckets 會(huì)發(fā)現(xiàn)根本無(wú)法獲取到buckets,仔細(xì)閱讀源碼會(huì)發(fā)現(xiàn)cache_t中提供了struct bucket_t *buckets()用于獲取buckets。所以如圖,通過(guò).buckets()獲取,sel同理。
2.buckets是存在散列表中,如果有多個(gè)buckets可以通過(guò)指針偏移獲取,再執(zhí)行[p method2]:

3.繼續(xù)執(zhí)行[p method3],會(huì)發(fā)現(xiàn)mask變成了7,occupied變成了1


需要了解為什么會(huì)這樣變化,我們需要從cache_t的插入源碼入手。

ALWAYS_INLINE
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;  // 擴(kuò)容兩倍 4
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
        reallocate(oldCapacity, capacity, true);  // 內(nèi)存 庫(kù)容完畢
    }

    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);
}
  1. 當(dāng)緩存為空時(shí),會(huì)初始化緩存
if (slowpath(isConstantEmptyCache())) {
        // Cache is read-only. Replace it.
        if (!capacity) capacity = INIT_CACHE_SIZE;
        reallocate(oldCapacity, capacity, /* freeOld */false);
    }

2.當(dāng)緩存不為空,且不大于總大小的3/4減1時(shí),不進(jìn)行任何操作(#define CACHE_END_MARKER 1)

    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.
    }

3.當(dāng)總大小不夠時(shí),會(huì)進(jìn)行擴(kuò)容

    else {
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;  // 擴(kuò)容兩倍 4
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
        reallocate(oldCapacity, capacity, true);  // 內(nèi)存 庫(kù)容完畢
    }

如此可以找到原因:第一次申請(qǐng)空間為4,maskcapacity-1=3,method1method2插入時(shí),滿足newOccupied + CACHE_END_MARKER <= capacity / 4 * 3,而當(dāng)method3插入時(shí),newOccupied變?yōu)?code>3,3+1>4/4*3所以要進(jìn)行擴(kuò)容,原有緩存被舍去,只插入了method3,故occupied變成了1,mask變成了7。

其他

cache的插入時(shí)亂序的。

    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));
  1. cache的插入不是順序插入,是先做一次哈希計(jì)算,由這個(gè)值開(kāi)始mask_t begin = cache_hash(sel, m)

2.cache當(dāng)哈希計(jì)算出的位置中值為空時(shí),插入。

 if (fastpath(b[i].sel() == 0)) {
            incrementOccupied();
            b[i].set<Atomic, Encoded>(sel, imp, cls);
            return;
        }

3.哈希計(jì)算的位置值相同時(shí)跳過(guò),不再插入。

        if (b[i].sel() == sel) {
            // The entry was added to the cache by some other thread
            // before we grabbed the cacheUpdateLock.
            return;
        }

4.繼續(xù)哈希,直到找到合適的位置插入while (fastpath((i = cache_next(i, m)) != begin))

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容