Search code examples
iosswiftdatabaserealmrealm-mobile-platform

Realm iOS: how expensive is it to initiate Realm with a bundled db?


I'm using Realm for my project and I need to query a list of results in a non-UI-blocking thread (ie. background), read only; I consulted Realm's doc, it seems that I need to create the Realm instance in the same thread where it's been queried, so I wonder how expensive it is if I re-create Realm object every time?

@IBAction func scoreAction(_ sender: Any?) {
    DispatchQueue.global(qos: .background).async }
        let scores = loadScore()
        DispatchQueue.main.async {
            display(scores)
        }
    }
}

then:

func loadScore() -> [Score] {
    let realm = try! Realm(configuration: config)
    return realm.objects(Score.self).filter("some criteria")
}

Solution

  • Calling the initializer of Realm doesn't actually create a new database, it simply creates a new reference to the existing Realm database at the location specified in the RealmConfiguration used in the initializer of Realm. This means that in general, once the database is open, creating a new reference to it by calling Realm() or Realm(configuration: config) isn't expensive computationally. So in general, it can often make more sense to create a new reference to your Realm when switching between threads.

    Of course, to know for sure which is the more optimal way for your specific use case, you'll actually need to run tests on a real device, but as long as you're not switching between threads frequently (say several times in a single second), you should be fine with creating a new reference to Realm on both threads after switching between them.