内联缓存与多态内联技术
在Swift中手动实现类似JIT的内联缓存,通过方法指针修补加速协议方法派发 · 难度:入门 · +10XP
内联缓存与多态内联技术
动态派发是协议开销的主要来源,内联缓存(Inline Cache)通过缓存目标类型的方法地址避免重复查找。本教程利用Swift的@dynamicCallable与UnsafePointer在运行时修补调用点,实现一个简易内联缓存系统。
@dynamicCallable
struct InlineCache {
private var cachedImpl: (@convention(thin) (Any) -> Void)?
func dynamicallyCall(withArguments args: [Any]) {
let target = args[0]
let typeID = ObjectIdentifier(type(of: target))
if let impl = lookupCache(typeID) {
impl(target)
} else {
let impl = compileDispatch(typeID)
cache(typeID, impl)
impl(target)
}
}
private func lookupCache(_ id: ObjectIdentifier) -> ((Any) -> Void)? { nil }
private func compileDispatch(_ id: ObjectIdentifier) -> ((Any) -> Void) { { _ in } }
}