【问题标题】:Swifty JSON Performance degradation with Swift3, XCode8, iOS10Swift3、XCode8、iOS10 的 Swifty JSON 性能下降
【发布时间】:2016-10-06 16:13:41
【问题描述】:

我一直在我的应用程序中使用 SwiftyJSON 进行 JSON 解析。我最近将我的应用程序升级到 Swift3 并观察到严重的性能问题。我试图将问题隔离到一个小项目中。我正在考虑切换到不同的库或本地化(但这在我的应用程序中有很多工作),但想看看社区中是否有人观察到类似的问题。感谢您提供任何帮助,并提前致谢。

以下代码过去在 Swift2 中需要亚秒级,但在使用 Swift3 的发布可执行文件中需要 15 秒:

func parseSampleJson() {
        let st = NSDate()

        let file:NSString = Bundle.main.path(forResource: "testJson", ofType: "json")! as NSString
        let jsonData:NSData = NSData.dataWithContentsOfMappedFile(file as String) as! NSData
        let json = JSON(data: jsonData as Data)

        let dataJson = json["data"]
        for (_, subJson): (String, JSON) in dataJson {
//            NSLog("Name = " + subJson["Name"].stringValue)
            let castes = subJson["Castes"]
            for (_, cn): (String, JSON) in castes {
//                NSLog("  Name = " + cn["Name"].stringValue)
            }
        }
        let et = NSDate()
        let timeTaken = et.timeIntervalSince(st as Date)
        NSLog("******* Time taken = \(timeTaken)")
    }

完整的项目在 github 上https://github.com/good2best123/SwiftyJSONTest

【问题讨论】:

  • 这看起来还是个问题!你找到解决方案了吗?

标签: swift ios10 swifty-json


【解决方案1】:

您可以尝试升级到版本3.1.3。问题已解决there

【讨论】:

    【解决方案2】:

    我看到了同样的行为。 SwiftyJSON 2.3.2/Swift 2.2 和 SwiftyJSON 3.1.1/Swift 3.0 之间似乎存在显着的性能退化。

    首先我会尝试使用索引来访问 JSON 数据。

    let dataJson = json["data"]
    let n = dataJson.count
    
    for djIndex in 0...n-1 {
      let subJson = dataJson[djIndex]
      let castes = subJson["Castes"]
      let castesCount = castes.count
    
    //            NSLog("Name = " + subJson["Name"].stringValue)
    
      for cnIndex in 0..castesCount-1{
        let cn = castes[cnIndex]
        //                NSLog("  Name = " + cn["Name"].stringValue)
      }
    
    }
    

    从我对代码进行的测试中,很明显 JSON 数组解析是在使用 CPU 周期。

    将任何多次使用的 JSON 属性缓存到一个变量中,虽然丑陋,但将我的 Swift 3/SwiftJSON 3.1.1 代码的性能带回了原始 Swift 2.2/SwiftyJSON 2.3.2 代码的性能。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 2014-05-19
      • 2013-12-24
      相关资源
      最近更新 更多