-
Notifications
You must be signed in to change notification settings - Fork 84
5. SmartCodable Performance
intsig171 edited this page Apr 10, 2025
·
3 revisions
// 减少动态派发开销,is 检查是编译时静态行为,比 as? 动态转换更高效。
fileprivate func didFinishMapping<T>(_ decodeValue: T) -> T {
// Properties wrapped by property wrappers don't conform to SmartDecodable protocol.
// Here we use PostDecodingHookable as an intermediary layer for processing.
// 减少动态派发开销,is 检查是编译时静态行为,比 as? 动态转换更高效。
guard T.self is SmartDecodable.Type else { return decodeValue }
if var value = decodeValue as? SmartDecodable {
value.didFinishMapping()
if let temp = value as? T { return temp }
} else if let value = decodeValue as? PostDecodingHookable {
if let temp = value.wrappedValueDidFinishMapping() as? T {
return temp
}
}
return decodeValue
}
用到再换成,避免无用换成。 /// Creates and stores a snapshot of initial values for a Decodable type /// - Parameter type: The Decodable type to cache func cacheSnapshot(for type: T.Type) { if let object = type as? SmartDecodable.Type {
let snapshot = DecodingSnapshot()
// [initialValues] Lazy initialization:
// Generate initial values via reflection only when first accessed,
// using the recorded objectType to optimize parsing performance.
snapshot.objectType = object
snapshots.append(snapshot)
}
}