Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用iOS'进行缓慢的JSON解析;NSJ串行化_Ios_Swift_Performance_Instruments_Foundation - Fatal编程技术网

使用iOS'进行缓慢的JSON解析;NSJ串行化

使用iOS'进行缓慢的JSON解析;NSJ串行化,ios,swift,performance,instruments,foundation,Ios,Swift,Performance,Instruments,Foundation,在使用iOS基金会的NSJSONSerialization解析大型JSON时,我发现了性能问题。JSON大致如下: { "things": [ { "id": 123, "name": "Foo", "weight": 12.34, ... } { "id": 456, "name": "Bar", "weight": 56.78, ... } ... ] } 大约有1000个对象,每个对象大约有50个名称/值对 解析代码大约为:

在使用iOS基金会的
NSJSONSerialization
解析大型JSON时,我发现了性能问题。JSON大致如下:

{
    "things": [
        { "id": 123, "name": "Foo", "weight": 12.34, ... }
        { "id": 456, "name": "Bar", "weight": 56.78, ... }
        ...
    ]
}
大约有1000个对象,每个对象大约有50个名称/值对

解析代码大约为:

let json = NSJSONSerialization.JSONObjectWithData(data, options: [])
let jsonDict = json as! [String : AnyObject]
let things = jsonDict["things"] as! [[String : AnyObject]]
for thing in things {
    ...
}
使用仪器进行评测时,大部分时间都花在第二次播放上(
json as![[String:AnyObject]]
),在iphone6上需要0.75秒,在ipad4(32位)上几乎需要3秒


这只是数据量的函数吗?毕竟,它必须将整个JSON层次结构转换成一个字典(尽管我很惊讶时间花在了转换上,而不是花在
JSONObjectWithData
)。由于JSON是如此扁平,也许我应该编写自己的SAX风格解析。

如果速度慢,那么使用
NSOperationQueue
或GCD在后台线程上解析它。还要尽量避免强制展开/施放物品:)施放物品有什么特殊原因吗?我相信在反序列化之后您仍然可以直接访问数据结构。@AndrewCarter我已经在后台运行了它,强制unwrp/cast只是为了简单起见example@zcui93
JSONObjectWithData
的返回类型是AnyObject,如何将其作为数组或字典访问?