Swift 并发操作慢 2 倍
Swift concurrent operation slower 2x times
我有一个很大的 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
块内。
如 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.
这意味着您不会通过尝试在多线程中写入而获得任何好处。
我有一个很大的 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
块内。 如 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.
这意味着您不会通过尝试在多线程中写入而获得任何好处。