Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred method to mass update in Realm?

Tags:

ios

swift

realm

I have 10,000 Person Objects in my Realm database, all I have are the IDs of each person. I've been profiling the different solutions I have come up with to update all the names on each Person object.

In my test application I retrieve all the IDs using the following.

The code below is only run to fetch IDs for the tests, in the real application I would already have the IDs

var ids = [String]()
for person in realm.objects(Person) {
    ids.append(person.id)
}

First approach to update all names for 10,000 Person objects

realm.write {
    let people = realm.objects(Person).filter("id IN %@", ids)
    for person in people {
        person.name = "lionpants"
    }
}

Second approach to update all names for 10,000 Person objects

realm.write {
    for id in ids {
        let person = realm.objectForPrimaryKey(Person.self, key: id)
        person?.name = "lionpants"
    }
}

Surprisingly both approaches averaged about 1200ms runtime (including fetching the IDs) using the Xcode Time Profiler (I thought the first approach with the predicate would be faster).

Personally, I prefer the second approach due to the lack of predicates. But, is there a preferred/different approach when mass updating with Realm? Maybe I'm missing some built in functions?

like image 466
lionpants Avatar asked Jul 24 '15 17:07

lionpants


1 Answers

realm.write {
    let people = realm.objects(Person).filter("id IN %@", ids)
    people.setValue("lionpants", forKey: "name")
}

Should be slight faster, and in general using KVC on results like that will be more performant, as Realm can take some shortcuts under the hood.

like image 126
segiddins Avatar answered Sep 23 '22 19:09

segiddins