Realm插入的CPU使用率很高

时间:2018-04-17 10:10:09

标签: ios swift memory realm cpu-usage

我循环遍历多个JSON文件,处理数据并插入Realm。这可能发生在后台线程上。

一旦我开始处理文件,我的CPU就可以高达230%。它使用大约130的中等CPU从50 - 230上下跳转。我使用了dispatchqueue背景包装器并且还使用了autoreleaspool并尝试在我的插入函数中拆分我的提交,但我无法将此CPU降低到可接受的水平量。

有什么我想念的吗?如何改善这些方法的CPU使用率?

override open class func processData(json: Data, 
                                     _cleanSync: Bool, 
                                     completionHandler: @escaping (Int, [Int]) -> ()){

    print("Helper_WorkShift processData")
    var control : [Int] = []
    if let syncReponse = (try? JSONSerialization.jsonObject(with: json, options: [])) as? [[String: Any]] {

        var dataList : [STD_TA_shifts] = []

        for item in syncReponse
        {
            autoreleasepool{
                if let jsonStr = item["data"] as? String {
                    let addItem = STD_TA_shifts(workShiftJsonStr : jsonStr)
                    dataList.append(addItem)
                    control.append(addItem._id)
                }
            }
        }

        if (dataList.count > 0)
        {
            insertWorkShiftList(workShiftList : dataList)
        }
        dataList.removeAll()
    }

    completionHandler(control.count, control)
}

插入列表方法:

public class func insertWorkShiftList(workShiftList : [STD_TA_shifts])
{
    //print("in insertEmployeeList")
    DispatchQueue(label: "background").async {
        if (workShiftList.count == 0){
            return
        }

        // Bulk insert
        autoreleasepool {
            do {
                var realm : Realm? = try Realm()

                var batch = 0
                let total = workShiftList.count

                realm?.beginWrite()
                for i in 0...total - 1 {
                    autoreleasepool {
                        realm?.add(workShiftList[i], update: true)
                    }
                    batch = batch + 1
                    if batch == 10 {
                        batch  = 0

                        try realm?.commitWrite()

                        if i < (total - 1) {
                            realm?.beginWrite()
                        }
                    }
                    else if i == (total - 1) {
                        try realm?.commitWrite()
                    }
                }

                realm = nil
            }
            catch let error as NSError {
                print("error realm \(error.localizedDescription)")
            }
        }
    }
}

0 个答案:

没有答案