OC类的结构-cache_t

OC中的类是一个继承自objc_object的objc_class结构体。

struct objc_class : objc_object {
    // Class ISA;          //继承自objc_object的isa指针
    Class superclass;  //父类
    cache_t cache;             // formerly cache pointer and vtable
    class_data_bits_t bits;    //包含类的属性和方法
}

cache_t是做什么的?从字面上理解是缓存,那又存储什么?

cache_t是缓存空间,主要存储sel和imp

查看objc4-818.2 中cache_t结构体源码

struct cache_t {
    explicit_atomic _bucketsAndMaybeMask;
    union {
        struct {
            explicit_atomic    _maybeMask;
#if __LP64__
            uint16_t                   _flags;
#endif
            uint16_t                   _occupied;
        };
        explicit_atomic _originalPreoptCache;
    };

  .....
}

上面的变量是占用cache_t的内存。其余静态变量和函数都不在cache_t内存中。
联合体位域中 _originalPreoptCache_maybeMask_flags_occupied是共用内存空间。

_bucketsAndMaybeMask是bucket 和mask共同占用8个字节。setBucketsAndMask函数进行设置bucket和mask的值。

void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
{
    uintptr_t buckets = (uintptr_t)newBuckets;
    uintptr_t mask = (uintptr_t)newMask;

    ASSERT(buckets <= bucketsMask);
    ASSERT(mask <= maxMask);
    // maskshift = 48 ,newmask在高16位,低48位为bucket
    _bucketsAndMaybeMask.store(((uintptr_t)newMask << maskShift) | (uintptr_t)newBuckets, memory_order_relaxed);
    _occupied = 0;
}

cache_t的内存结构大致可以如下

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

struct lg_bucket_t {
    SEL _sel;
    IMP _imp;
};

struct lg_cache_t {
    struct lg_bucket_t * _buckets;
    mask_t _mask;          //缓存空间大小
    uint16_t _flags;
    uint16_t _occupied;    //占用了多少缓存空间
};
struct lg_objc_class {
    Class ISA;
    Class superclass;
    struct lg_cache_t cache;             // formerly cache pointer and vtable
    struct lg_class_data_bits_t bits;    // class_rw_t * plus custom rr/alloc flags
};


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
      
        LGPerson *p  = [LGPerson alloc];
        Class pClass = [LGPerson class];
//        p.lgName     = @"Cooci";
//        p.nickName   = @"KC";
        // 缓存一次方法 sayHello
        // 4
        [p sayHello];
        [p sayCode];
        
        struct lg_objc_class *lg_pClass = (__bridge struct lg_objc_class *)(pClass);
        
        NSLog(@" %hu - %u",lg_pClass->cache._occupied,lg_pClass->cache._mask);
        
        for (mask_t i = 0; icache._mask; i++) {
             // 打印获取的 bucket
            struct lg_bucket_t bucket = lg_pClass->cache._buckets[i];
            NSLog(@"%@ - %p",NSStringFromSelector(bucket._sel),bucket._imp);
        }
    }
    return 0;
}

输出如下


image.png

既然是缓存那么一定会有缓存的插入方法cache_t::insert()

void cache_t::insert(SEL sel, IMP imp, id receiver)
{
    runtimeLock.assertLocked();

    // Never cache before +initialize is done
    if (slowpath(!cls()->isInitialized())) {
        return;
    }

    if (isConstantOptimizedCache()) {
        _objc_fatal("cache_t::insert() called with a preoptimized cache for %s",
                    cls()->nameForLogging());
    }

#if DEBUG_TASK_THREADS
    return _collecting_in_critical();
#else
#if CONFIG_USE_CACHE_LOCK
    mutex_locker_t lock(cacheUpdateLock);
#endif

    ASSERT(sel != 0 && cls()->isInitialized());

    // Use the cache as-is if until we exceed our expected fill ratio.
    //1.缓存占用+1操作
    mask_t newOccupied = occupied() + 1;
    //2. 获取老的缓存容量
    unsigned oldCapacity = capacity(), capacity = oldCapacity;
    //3. 判断缓存空间是否为空
    if (slowpath(isConstantEmptyCache())) {
        // Cache is read-only. Replace it.
        //3.1 重新分配缓存
        if (!capacity) capacity = INIT_CACHE_SIZE;
        reallocate(oldCapacity, capacity, /* freeOld */false);
    }
    //4. newOccupied + 1 <= capacity*0.75 ,缓存容量小于缓存空间的0.75,跳过
    else if (fastpath(newOccupied + CACHE_END_MARKER <= cache_fill_ratio(capacity))) {
        // Cache is less than 3/4 or 7/8 full. Use it as-is.
    }
// 5 是否支持满缓存
#if CACHE_ALLOW_FULL_UTILIZATION
    else if (capacity <= FULL_UTILIZATION_CACHE_SIZE && newOccupied + CACHE_END_MARKER <= capacity) {
        // Allow 100% cache utilization for small buckets. Use it as-is.
    }
#endif
    else {
      // 6. 否则,就将原来的缓存扩容2倍
        capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
        if (capacity > MAX_CACHE_SIZE) {
            capacity = MAX_CACHE_SIZE;
        }
        //6.1 开辟新的换从空间,释放旧的缓存空间
        reallocate(oldCapacity, capacity, true);
    }
    //7.1获取缓存中buckets数组
    bucket_t *b = buckets();
    mask_t m = capacity - 1;
    //7.2使用hash值找出sel的起始位置
    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.
    do {
      //7.3 找出buckets数组中i位置的sel是否为空
        if (fastpath(b[i].sel() == 0)) {
          7.4. 空的,将缓存空间占用数+1
            incrementOccupied();
            b[i].set(b, sel, imp, cls());
            return;
        }
        //7.5 如果相等直接放回
        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)); //7. 6 产生hash碰撞查找下一个位置

    bad_cache(receiver, (SEL)sel);
#endif // !DEBUG_TASK_THREADS
}
  1. 缓存占用 occupied +1操作
  2. 获取现在的缓存容量capacity
  3. 判断缓存空间是否为空,否则跳过执行7
    3.1 重新分配缓存
  4. newOccupied + 1 <= capacity*0.75 ,缓存容量小于缓存空间的0.75,否则跳过执行7
  5. 是否支持满缓存, 否则7
  6. 就将原来的缓存扩容capacity 2倍
  7. 缓存操作
    7.1 获取缓存中buckets数组
    7.2 使用hash值找出sel在buckets插入的起始位置i
    7.3 找出buckets数组中i位置的sel是否为空,空的,将缓存空间占用数+1
    7.4 如果相等直接返回
    7.5 产生hash碰撞查找下一个插入的位置

其中reallocate

void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
{
    bucket_t *oldBuckets = buckets();
    bucket_t *newBuckets = allocateBuckets(newCapacity);
    setBucketsAndMask(newBuckets, newCapacity - 1);
    //释放旧缓存空间的buckets
    if (freeOld) {
        collect_free(oldBuckets, oldCapacity);
    }
}
void cache_t::collect_free(bucket_t *data, mask_t capacity)
{
#if CONFIG_USE_CACHE_LOCK
    cacheUpdateLock.assertLocked();
#else
    runtimeLock.assertLocked();
#endif

    if (PrintCaches) recordDeadCache(capacity);

    _garbage_make_room ();
    garbage_byte_size += cache_t::bytesForCapacity(capacity);
    garbage_refs[garbage_count++] = data;
    cache_t::collectNolock(false);
}

总结:

  1. cache_t是方法的缓存空间,主要使用buckets存储sel和imp。
  2. 插入sel和imp时,需要检查缓存空间是否足够,否则需要扩容两倍开启新的buckets,并对原有的buckets进行释放

你可能感兴趣的:(OC类的结构-cache_t)