iOS底层-cache_t分析

在之前我们已经分析过类的结构了,也具体分析过其中的isa、bits,现在我要开始分析一下cache:缓存


pic0

cache 的主要作用是存储类的方法,只有调用后才会缓存哦,并不是一开始加载就缓存的

@interface MCPerson : NSObject
{
    NSString *nickName;
}
@property (nonatomic,copy) NSString *name;
-(void)say1;
-(void)say2;
-(void)say3;
-(void)say4;
-(void)say5;
-(void)say6;
-(void)say7;
-(void)say8;
-(void)say9;
-(void)say10;
-(void)say11;
-(void)say12;
@end

@implementation MCPerson
-(void)say1{
    NSLog(@"%s",__func__);
}
-(void)say2{
    NSLog(@"%s",__func__);
}
-(void)say3{
    NSLog(@"%s",__func__);
}
-(void)say4{
    NSLog(@"%s",__func__);
}
-(void)say5{
    NSLog(@"%s",__func__);
}
-(void)say6{
    NSLog(@"%s",__func__);
}
-(void)say7{
    NSLog(@"%s",__func__);
}
-(void)say8{
    NSLog(@"%s",__func__);
}
-(void)say9{
    NSLog(@"%s",__func__);
}
-(void)say10{
    NSLog(@"%s",__func__);
}
-(void)say11{
    NSLog(@"%s",__func__);
}
-(void)say12{
    NSLog(@"%s",__func__);
}
@end

开始断点调试


pic2

当第一个方法都没调用的时候断住

(lldb) p/x MCPerson.class
(Class) $0 = 0x00000001000034c8 MCPerson
(lldb) p (cache_t*)0x00000001000034d8 //内存偏移16个字节,取出cache
(cache_t *) $1 = 0x00000001000034d8
(lldb) p *$1
(cache_t) $2 = {
  _buckets = {
    std::__1::atomic<bucket_t *> = 0x000000010032e440 {
      _sel = {
        std::__1::atomic<objc_selector *> = (null)
      }
      _imp = {
        std::__1::atomic<unsigned long> = 0
      }
    }
  }
  _mask = {
    std::__1::atomic<unsigned int> = 0//分配空间为0
  }
  _flags = 32804
  _occupied = 0 //数量0
}

当第一个方法调用后断住

2020-09-18 02:51:45.097235+0800 KCObjc[42706:2137752] -[MCPerson say1]
(lldb) p *$1
(cache_t) $3 = {
  _buckets = {
    std::__1::atomic<bucket_t *> = 0x0000000102900350 {
      _sel = {
        std::__1::atomic<objc_selector *> = ""
      }
      _imp = {
        std::__1::atomic<unsigned long> = 8376
      }
    }
  }
  _mask = {
    std::__1::atomic<unsigned int> = 3//开辟空间为3
  }
  _flags = 32804
  _occupied = 1//数量为1
}
(lldb) 

打印缓存的方法,注意,这里的buckets()是返回数组的第一个元素,如果要第二个元素可以p $3.buckets()[1]

(lldb) p $3.buckets()
(bucket_t *) $4 = 0x0000000102900350
(lldb) p *$4
(bucket_t) $5 = {
  _sel = {
    std::__1::atomic<objc_selector *> = ""
  }
  _imp = {
    std::__1::atomic<unsigned long> = 8376
  }
}
(lldb) p $5.sel()
(SEL) $6 = "say1"

这里说明的确方法调用后会缓存到cache中来

接下来再次调用余下的方法,直到最后一个方法

(lldb) p *$1
(cache_t) $8 = {
  _buckets = {
    std::__1::atomic<bucket_t *> = 0x00000001006489e0 {
      _sel = {
        std::__1::atomic<objc_selector *> = (null)
      }
      _imp = {
        std::__1::atomic<unsigned long> = 0
      }
    }
  }
  _mask = {
    std::__1::atomic<unsigned int> = 15//开辟的空间
  }
  _flags = 32804
  _occupied = 5//数量
}

如果一个一个断点慢慢走,会发现_occupied会不断重置然后递增,_mask的值也再不断增加,所以我们来看一下源码,了解一下其中的逻辑

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;
//    如果缓存为空,初始化capacity大小为4,occupied为1,mask_t = capacity -1
//     or
//     newOccupied + 1 <= 容量 /4 * 3 的时候不管
//     or
//     _occupied 重置为0 capacity = capacity * 2
    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.
    }
    else {
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
//调用这个方法后会重置_occupied、_mask
        reallocate(oldCapacity, capacity, true);
    }

    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(); // 在这里增长_occupied,标识有新的方法被缓存了
            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);// 缓存发生意外
}

ALWAYS_INLINE
void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
{
    bucket_t *oldBuckets = buckets();
    bucket_t *newBuckets = allocateBuckets(newCapacity);

    // Cache's old contents are not propagated. 
    // This is thought to save cache memory at the cost of extra cache fills.
    // fixme re-measure this

    ASSERT(newCapacity > 0);
    ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
//调用这个方法后,_occupied会被重置
    setBucketsAndMask(newBuckets, newCapacity - 1);
    
    if (freeOld) {
        cache_collect_free(oldBuckets, oldCapacity);
    }
}

#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED

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;//重置为0
#elif __x86_64__ || i386
    // ensure other threads see buckets contents before buckets pointer
    _buckets.store(newBuckets, memory_order::memory_order_release);
    
    // ensure other threads see new buckets before new mask
    _mask.store(newMask, memory_order::memory_order_release);
    _occupied = 0;//重置为0
#else
#error Don't know how to do setBucketsAndMask on this architecture.
#endif
}

总结:

  • 对象缓存是放在类的缓存列表中的。
  • 缓存列表本来为空,只有当第一次调用对象某一个实例时才会分配给一个缓存空间。
  • 缓存空间容量是弹性的,当容量达到一定程度时,- 缓存空间会重新分配,此时列表也会被清空。
  • 缓存列表中的方法缓存时乱序的,和缓存顺序及方法在类中的顺序无关。(当全部方法调用完后,从buckets数组中取,很多方法无法取出,而且是乱序的)
  • _occupied代表此时混存列表中已缓存方法的数量,每次都会重置;这里有疑问,下次继续深入了解,这个字段代表的含义
  • _mask和容量大小相关。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335