ios – Does Realm use a cached instance when repeatedly instantiating Realm()?


I have a SwiftUI app using Realm for data persistence. In my code, I am instantiating a new Realm instance each time I need to access the database, like this:

final class RealmDataManager {

  init() {}

  func getAccounts() -> Results<Account> {
    let realm = try! Realm() 
    return realm.objects(Account.self)
  }

  func addAccount(account: Account) {
    let realm = try! Realm()
    realm.add(account)
  }

According to the Realm documentation:

“Like any disk I/O operation, creating a Realm instance could sometimes fail if resources are constrained. In practice, this can only happen the first time a Realm instance is created on a given thread. Subsequent accesses to a Realm from the same thread will reuse a cached instance and will always succeed.”

http://realm.io.s3-website-us-east-1.amazonaws.com/docs/swift/latest/

My question is – even though I am creating a new Realm instance each time, will Realm actually use a cached instance behind the scenes when accessing the database from the same thread?

Or does instantiating a new Realm() each time force it to create separate instances that are not cached?

I am trying to understand if my current approach affects performance from not reusing a cached Realm instance, or if Realm handles that caching automatically despite instantiating Realm separately in code.

Any clarification is appreciated!

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img