HandyJSON
HandyJSON copied to clipboard
这个性能有点低怎么办
trafficstars
我就拿官方的 demo 去测试了,用的最简单的 json
let jsonString = "{"data":{"aInt":100,"aStr":"string data","id":1},"code":200,"biz":"social"}"
let result = Result<Model>.deserialize(from: jsonString)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print(CACurrentMediaTime())
for i in 1...200 {
self.deserialization()
}
print(CACurrentMediaTime())
}
200 个都需要 0.04s 在 60 帧的刷新率下完全不能在主线程转
有跟系统的提供的codeAble进行比对吗?
let jsonDic = ["doubleOptional":1.1, "stringImplicitlyUnwrapped":"hello", "int":1] as [String : Any]
系统提供的转模型:
/// 字典转模型
func toModel<T>(_ type: T.Type, value: Any) -> T? where T : Decodable {
guard let data = try? JSONSerialization.data(withJSONObject: value) else { return nil }
let decoder = JSONDecoder()
decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+Infinity", negativeInfinity: "-Infinity", nan: "NaN")
return try? decoder.decode(type, from: data)
}
let startTime = CACurrentMediaTime()
for _ in 1...200 {
tempModel = toModel(Model.self, value: jsonDic)
}
let endTime = CACurrentMediaTime()
print("time = \(endTime-startTime)") // time = 0.013348208332899958
耗时大概是: time = 0.013348208332899958
HandyJSON转模型:
let startTime = CACurrentMediaTime()
for _ in 1...200 {
tempModel = Model.deserialize(from: jsonDic)
}
let endTime = CACurrentMediaTime()
print("time = \(endTime-startTime)") // time = 0.011834375007310882
耗时大概是 time = 0.011834375007310882
结论:耗时差不多。
let jsonDic = ["doubleOptional":1.1, "stringImplicitlyUnwrapped":"hello", "int":1] as [String : Any]系统提供的转模型:
/// 字典转模型 func toModel<T>(_ type: T.Type, value: Any) -> T? where T : Decodable { guard let data = try? JSONSerialization.data(withJSONObject: value) else { return nil } let decoder = JSONDecoder() decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+Infinity", negativeInfinity: "-Infinity", nan: "NaN") return try? decoder.decode(type, from: data) } let startTime = CACurrentMediaTime() for _ in 1...200 { tempModel = toModel(Model.self, value: jsonDic) } let endTime = CACurrentMediaTime() print("time = \(endTime-startTime)") // time = 0.013348208332899958耗时大概是: time = 0.013348208332899958
HandyJSON转模型:
let startTime = CACurrentMediaTime() for _ in 1...200 { tempModel = Model.deserialize(from: jsonDic) } let endTime = CACurrentMediaTime() print("time = \(endTime-startTime)") // time = 0.011834375007310882耗时大概是 time = 0.011834375007310882
结论:耗时差不多。
是不是因为你的数据模型是NSObject的子类。解析swift的类应该会慢一点吧,Mirror开销会大一点吧。