我有一个大的 JSON 数组需要保存到 Realm,问题是这个操作持续大约 45 秒而且太长了。我尝试像这样为 JSON 数组中的每个元素同时运行保存操作:
for element in jsonArray { // jsonArray has about 25 elements
DispatchQueue.global(qos: .userInitiated).async {
let realm = try! Realm()
let savedObject = realm.objects(MyObject.self).filter("name == '\(element.name)'")
for subElement in element { // element is an array that has around 1000 elements
let myModel = MyModel(initWith: subElement) // MyModel initialization is a simple light weight process that copies values from one model to another
savedObject.models.append(myModel)
}
}
}
当我尝试运行相同的代码但使用 DispatchQueue.main.async
时,即使它不是并发的,它的完成速度也快了大约 2 倍。我还尝试以服务质量 .userInteractive
运行上面的代码,但速度相同。
当我运行这段代码时,CPU 利用率约为 30%,内存约为 45 MB。是否有可能加快此操作或我到达了死胡同?
最佳答案
- 整个循环应该在
DispatchQueue.global(qos: .userInitiated).async
block 内。 如 the Realm website 中所述:
Realm write operations are synchronous and blocking, not asynchronous. If thread A starts a write operation, then thread B starts a write operation on the same Realm before thread A is finished, thread A must finish and commit its transaction before thread B’s write operation takes place. Write operations always refresh automatically on beginWrite(), so no race condition is created by overlapping writes.
这意味着尝试在多线程中编写不会获得任何好处。
关于ios - Swift 并发操作慢 2 倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55240991/