preface

What is cache? Cache? Cache what? How to cache? What is the structure of a cache? Caching process? Start this article with these questions in mind.

The preparatory work

  • Objc4-818.2 – the source code

Cache_t structure

private:
    explicit_atomic<uintptr_t> _bucketsAndMaybeMask;
    union {
        struct {
            explicit_atomic<mask_t>    _maybeMask;
#if __LP64__
            uint16_t                   _flags;
#endif
            uint16_t                   _occupied;
        };
        explicit_atomic<preopt_cache_t *> _originalPreoptCache;
    };
    
    
    
    void incrementOccupied();

    void setBucketsAndMask(**struct** bucket_t *newBuckets, mask_t newMask);

    void reallocate(mask_t oldCapacity, mask_t newCapacity, **bool** freeOld);

    void collect_free(bucket_t *oldBuckets, mask_t oldCapacity);

    static bucket_t *emptyBuckets();

    static bucket_t *allocateBuckets(mask_t newCapacity);

    static bucket_t *emptyBucketsForCapacity(mask_t capacity, bool allocate = true);
    
    struct bucket_t *buckets() const;

    static struct bucket_t * endMarker(**struct** bucket_t *b, uint32_t cap);
  
Copy the code

We can probably see that buckets are important, EmptyBuckets,struct bucket_t *buckets(),static bucket_t *allocateBuckets(mask_t newCapacity) Let’s go inside and take a look at the structure.

The structure of bucket_t

struct bucket_t {

private:

#if __arm64__

    explicit_atomic<uintptr_t> _imp;

    explicit_atomic<SEL> _sel;

#else

    explicit_atomic<SEL> _sel;
    explicit_atomic<uintptr_t> _imp;
    }    
Copy the code

Sel,imp this is the method number and function pointer address! The bucket contains SEL and IMP.

  • A cache caches methods

Structure diagram of bucket_t