iOS cache_t結(jié)構(gòu)分析

  1. cache_t源碼結(jié)構(gòu)
    精簡后的cache_t源碼如下:
struct cache_t {
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
    // MAC
    struct bucket_t * _buckets;
    uint32_t _mask;
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
    //真機(jī)
    uintptr_t _maskAndBuckets;
    mask_t _mask_unused;
    
    static constexpr uintptr_t maskShift = 48;
    static constexpr uintptr_t maskZeroBits = 4;
    static constexpr uintptr_t maxMask = ((uintptr_t)1 << (64 - maskShift)) - 1;
    static constexpr uintptr_t bucketsMask = ((uintptr_t)1 << (maskShift - maskZeroBits)) - 1;
#else
#error Unknown cache mask storage type.
#endif
    
    uint16_t _flags;
    uint16_t _occupied;//占用的個(gè)數(shù)

public:
    static bucket_t *emptyBuckets();
    struct bucket_t *buckets();
    uint32_t mask();
    uint32_t occupied();
    void incrementOccupied();
    void setBucketsAndMask(struct bucket_t *newBuckets, uint32_t newMask);
    void initializeToEmpty();

    unsigned capacity();
    bool isConstantEmptyCache();
    bool canBeFreed();
};
void cache_t::incrementOccupied() 
{
    _occupied++;
}

可以看到有個(gè)重要的函數(shù)void incrementOccupied();,字面意思增加占用的個(gè)數(shù),該函數(shù)只對內(nèi)部成員變量加1操作哎壳。在源碼中全局搜索調(diào)用,即可看到在cache_t::insert函數(shù)中調(diào)用蔬充。

ALWAYS_INLINE
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
    //occupied() 獲取_occupied變量
    mask_t newOccupied = occupied() + 1;//因?yàn)橐略鲆粋€(gè)緩存羽莺,所以+1
    unsigned oldCapacity = capacity(), capacity = oldCapacity;
    if (slowpath(isConstantEmptyCache())) {
        // Cache is read-only. Replace it.
        //如果之前沒有緩存,開辟大小為4的內(nèi)存
        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.
        //如果新的占用個(gè)數(shù)加1  小于等于  capacity的四分之三 則繼續(xù)
    }
    else {
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
        //否則進(jìn)行擴(kuò)容到 capacity的二倍
        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);//通過hash計(jì)算出要存放的index
    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.
    //確保計(jì)算出存放的index沒有被占用猬错,否則繼續(xù)計(jì)算index
    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);
}

2. 模仿cache_t結(jié)構(gòu)窗看,進(jìn)行探索

typedef uint32_t mask_t;  // x86_64 & arm64 asm are less efficient with 16-bits

struct bucket_t {
    SEL _sel;
    IMP _imp;
};

struct ls_cache_t {
    struct bucket_t * _buckets;
    mask_t _mask;
    uint16_t _flags;
    uint16_t _occupied;
};

//不影響cache_t獲取,所以寫個(gè)空結(jié)構(gòu)體類型
struct ls_class_data_bits_t {

};

struct ls_objc_class {
    Class ISA;
    Class superclass;
    struct ls_cache_t cache;             // formerly cache pointer and vtable
    struct ls_class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
};

void printCachet(Class pClass) {
    struct ls_objc_class *ls_class = (__bridge struct ls_objc_class *)(pClass);
    
    uint16_t occupied = ls_class->cache._occupied;
    mask_t mask = ls_class->cache._mask;
    
    printf("cache_t._occupied = %d cache_t._mask = %d \n", occupied, mask);
    for (int i = 0; i < mask; i++) {
        struct bucket_t bucket = ls_class->cache._buckets[i];
        printf("sel=%s  imp=%p\n", [NSStringFromSelector(bucket._sel) UTF8String], bucket._imp);
    }
    printf("----------------------------------\n");
}


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        LSPerson *person = [LSPerson alloc];
        
        Class pClass = [LSPerson class];
        
        printCachet(pClass);
        [person eat];
        [person run];
        printCachet(pClass);
        [person sleep];
        [person smile];
        printCachet(pClass);
        

    }
    return 0;
}
//output
//不調(diào)用方法時(shí)倦炒,_occupied = 0显沈, _mask = 0
cache_t._occupied = 0 cache_t._mask = 0 
----------------------------------
2020-09-17 17:43:11.080167+0800 Cache_t_Analyze[64281:11027140] -[LSPerson eat]
2020-09-17 17:43:11.080673+0800 Cache_t_Analyze[64281:11027140] -[LSPerson run]
//調(diào)用2個(gè)方法后 _occupied = 2,_mask = 4 - 1
cache_t._occupied = 2 cache_t._mask = 3 
sel=run  imp=0x2c90
sel=(null)  imp=0x0
sel=eat  imp=0x2ce0
----------------------------------
2020-09-17 17:43:11.080923+0800 Cache_t_Analyze[64281:11027140] -[LSPerson sleep]
2020-09-17 17:43:11.080973+0800 Cache_t_Analyze[64281:11027140] -[LSPerson smile]
//調(diào)用4個(gè)方法逢唤,由于在調(diào)用第三個(gè)方法時(shí)觸發(fā)了擴(kuò)容拉讯,清空之前的緩存,所以只緩存了調(diào)用的第三個(gè)和第四個(gè)方法鳖藕,但容量擴(kuò)容到了8
//所以 _occupied = 2  _mask = 8 - 1
cache_t._occupied = 2 cache_t._mask = 7 
sel=smile  imp=0x2c70
sel=(null)  imp=0x0
sel=(null)  imp=0x0
sel=(null)  imp=0x0
sel=(null)  imp=0x0
sel=(null)  imp=0x0
sel=sleep  imp=0x2c40
----------------------------------
Program ended with exit code: 0
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末魔慷,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子著恩,更是在濱河造成了極大的恐慌院尔,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件喉誊,死亡現(xiàn)場離奇詭異邀摆,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)裹驰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進(jìn)店門隧熙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人幻林,你說我怎么就攤上這事贞盯。” “怎么了沪饺?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵躏敢,是天一觀的道長。 經(jīng)常有香客問我整葡,道長件余,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮啼器,結(jié)果婚禮上旬渠,老公的妹妹穿的比我還像新娘。我一直安慰自己端壳,他們只是感情好告丢,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著损谦,像睡著了一般岖免。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上照捡,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天颅湘,我揣著相機(jī)與錄音,去河邊找鬼栗精。 笑死闯参,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的术羔。 我是一名探鬼主播赢赊,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼级历!你這毒婦竟也來了释移?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤寥殖,失蹤者是張志新(化名)和其女友劉穎玩讳,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嚼贡,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡熏纯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了粤策。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片樟澜。...
    茶點(diǎn)故事閱讀 40,503評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖叮盘,靈堂內(nèi)的尸體忽然破棺而出秩贰,到底是詐尸還是另有隱情,我是刑警寧澤柔吼,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布毒费,位于F島的核電站,受9級特大地震影響愈魏,放射性物質(zhì)發(fā)生泄漏觅玻。R本人自食惡果不足惜想际,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望溪厘。 院中可真熱鬧胡本,春花似錦、人聲如沸桩匪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽傻昙。三九已至,卻和暖如春彩扔,著一層夾襖步出監(jiān)牢的瞬間妆档,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工虫碉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留贾惦,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓敦捧,卻偏偏與公主長得像须板,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子兢卵,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評論 2 359