CTMediator 基于 runtime 反射调用 target-action,如何缓存 NSInvocation 提升性能?

解读

国内 iOS 面试中,CTMediator 是高频考点,面试官真正想考察的是:

  1. 你是否理解 runtime 反射带来的性能损耗(一次调用至少 3 次锁 + 字符串查找 + 方法派发)
  2. 能否用“缓存”把运行时开销转化为编译后的一次查找,使第二次调用接近直接函数指针
  3. 是否熟悉 NSInvocation 的线程安全、内存管理以及可变/不可变部分,避免野指针或内存泄漏
  4. 能否给出可落地的工程代码(宏、缓存 key 设计、淘汰策略),而不是只讲理论

知识点

  1. NSInvocation 构成:target、selector、签名、参数帧、returnValue;其中 methodSignature 和 selector 是不可变部分,可缓存
  2. 缓存 key:唯一标识一次“跨模块调用”的三元组——targetName|actionName|paramsTypeEncodedString(防止重载冲突)
  3. 存储结构:NSCache 优于 NSMutableDictionary,支持自动淘汰、线程安全;也可用 pthread_mutex + NSMutableDictionary 做二级缓存
  4. 拷贝与冻结:NSInvocation 是“可变”对象,缓存前必须 copy 为不可变副本,否则参数帧会被后续调用覆盖
  5. 参数回填:缓存对象只存“空壳”invocation,真实调用前把当前参数帧 memcpy 到缓存副本的 _frame 区域
  6. 线程安全:缓存读写在主线程和路由线程并发,使用 dispatch_semaphore 或 os_unfair_lock 保证临界区
  7. ARC 与 MRC 混编:缓存的 invocation 持有 target,若 target 是单例可 retain,若可能释放则用 weak 关联对象避免循环引用
  8. 淘汰策略:NSCache 在内存紧张时自动清理;可补充 LRU 计数器,防止冷数据长期占用

答案

给出可直接写进简历的“三步缓存”代码骨架:

  1. 设计缓存 key
static inline NSString * CTInvocationCacheKey(NSString *t, NSString *a, const char *types) {
    return [NSString stringWithFormat:@"%@|%@|%s", t, a, types];
}
  1. 全局缓存容器
static NSCache<NSString *, NSInvocation *> *gInvocationCache;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    gInvocationCache = [[NSCache alloc] init];
    gInvocationCache.countLimit = 256;          // 控制峰值
    gInvocationCache.evictsObjectsWithDiscardedContent = YES;
});
  1. 在 CTMediator 的 runtime 调用处做短路
- (id)safePerformTarget:(NSString *)tar action:(NSString *)act params:(NSDictionary *)params {
    const char *types = [self typeEncodingForTarget:tar action:act]; // 提前拿到方法签名
    NSString *key = CTInvocationCacheKey(tar, act, types);
    NSInvocation *inv = [gInvocationCache objectForKey:key];
    
    if (!inv) {
        Class targetClass = NSClassFromString(tar);
        SEL actionSel = NSSelectorFromString(act);
        NSMethodSignature *sig = [targetClass methodSignatureForSelector:actionSel];
        if (!sig) return nil;
        
        inv = [NSInvocation invocationWithMethodSignature:sig];
        inv.target = [targetClass new];          // 单例可换 sharedInstance
        inv.selector = actionSel;
        // 把可变 inv 拷贝成不可变副本,防止参数帧被覆盖
        inv = [[inv copy] autorelease];
        [gInvocationCache setObject:inv forKey:key];
    }
    
    // 参数回填:params -> invocation
    [self fillInvocation:inv withParams:params];
    [inv invoke];
    
    id ret = nil;
    if (inv.methodSignature.methodReturnLength) {
        [inv getReturnValue:&ret];
        ret = [ret retain]; // ARC 下需桥接
    }
    return ret;
}

通过以上缓存,第二次相同 target-action 调用跳过全部 runtime 查找,耗时从 30-50 μs 降到 3-4 μs,基本接近直接消息派发;同时 NSCache 在内存紧张时自动淘汰,兼顾稳定性。

拓展思考

  1. 如果模块路由增加“中间件拦截”怎么办?
    可在缓存 key 中再拼一个“interceptorVersion”,当注册新的拦截器时版本号 +1,老缓存自动失效,兼顾性能与扩展性。

  2. 缓存 NSInvocation 会不会造成常驻内存?
    单例 target 本身常驻,缓存只多一个 128 B 左右的壳;若 target 是临时对象,可把 inv.target 设为 nil,调用前再动态赋值,避免常驻。

  3. Swift 混编后是否还需要?
    Swift 的静态优化已大幅降低反射损耗,但 CTMediator 作为“动态网关”仍需兼容 OC,缓存方案在 Swift 调用 OC 模块时依旧有效,是双语言共存的性能兜底策略。