iOS cache_t结构分析

  1. cache_t源码结构
    精简后的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
    //真机
    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;//占用的个数

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++;
}

可以看到有个重要的函数void incrementOccupied();,字面意思增加占用的个数,该函数只对内部成员变量加1操作。在源码中全局搜索调用,即可看到在cache_t::insert函数中调用。

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;//因为要新增一个缓存,所以+1
    unsigned oldCapacity = capacity(), capacity = oldCapacity;
    if (slowpath(isConstantEmptyCache())) {
        // Cache is read-only. Replace it.
        //如果之前没有缓存,开辟大小为4的内存
        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.
        //如果新的占用个数加1  小于等于  capacity的四分之三 则继续
    }
    else {
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
        //否则进行扩容到 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计算出要存放的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.
    //确保计算出存放的index没有被占用,否则继续计算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结构,进行探索

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获取,所以写个空结构体类型
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
//不调用方法时,_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]
//调用2个方法后 _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]
//调用4个方法,由于在调用第三个方法时触发了扩容,清空之前的缓存,所以只缓存了调用的第三个和第四个方法,但容量扩容到了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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270