Couchbaselite swift (ios) upsert is too slow

I’m adding aprox 1 Million records in database. I’m doing upsert (code snippet below).
It is processing 80-100 records per second and this number reduces as data grows in DB.

SDK version

pod 'CouchbaseLite-Swift', '3.1.1'

Please let me know if I’m doing anything wrong here.

private func upsertObjects(_ objects: [[String: Any]], inTable table: String, skipDirty: Bool = true, replace: Bool = true) -> Bool {

        do {
            ADPLog.Debug("start batch")
            try database.inBatch {
                for object in objects {
                    guard let objectId = object["id"] as? String else {
                        continue
                    }
                    let existingDoc = try database.defaultCollection().document(id: objectId)?.toDictionary()
                    if skipDirty, let existingDoc, isDirty(json: existingDoc) {
                        continue
                    }
                    var updatedJSON = object
                    if replace, let existingDoc {
                        updatedJSON = mergeJSON(existingDoc, updatedJSON)
                    }
                    let mutableDoc = MutableDocument(id: objectId, data: updatedJSON)
                    mutableDoc.setValue(table, forKey: DOCTYPE)
                    try database.defaultCollection().save(document: mutableDoc)
                }
            }
            ADPLog.Debug("end batch")
            return true
        }
        catch {
            ADPLog.Error(error.localizedDescription)
            return false
        }
    }

    private func isDirty(json: [String: Any]) -> Bool {
        guard let dirtyFlag = json[IS_DIRTY] as? Bool, dirtyFlag == true else {
            return false
        }
        return true
    }

I’m not a cblite guy, but look at the served dashboard to see what the server is doing during the inserts.
Also - you might.get better performance by using smaller batches.

Thanks for the inputs. These upserts are on local copy of DB. And I’m adding data in chunks of 20k records.

Can you try to do the time profiling with XCode and share the result?

Hi Pasin, attached is the screenshot of time profiler. Upsert operation for 20k records took ~18 sec, when I have only 20k existing record in DB.

It’s not clear where the time most spent in the save method. If you clicked the > arrow on the [CBLCollection saveDocument:concurrencyControl:error], will it show more information?

Also, are you testing on the actual iPhone device or the simulator? If it’s an actual device, can you provide the info about the device including the iOS version?

What is the general size of the documents (and blobs if any)? If you can provide an example doc, it will be very helpful so we could use that similar docs to test it out.