Is closing and reopening Realm instances bad for performance?

浪尽此生 提交于 2019-12-03 03:54:10
Christian Melchior

Realm uses a reference counted thread local cache + optimized schema validation. It means that as long as you have at least one instance open on a thread calling Realm.getInstance() it is just a HashMap lookup.

If you have one instance open on any thread, we skip schema validation on other threads even though it is the first instance opened there.

If you close all instances on a given Thread we will free the thread local memory and it will need to be reallocated for the next instance on that thread.

If you close all instances on all threads you will have a "cold boot" which is the most expensive as we need to allocate memory + do a schema validation.

Best practice is to keep the Realm instance open for as long as your thread lives. For the UI thread that is easiest done using the pattern described here: https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances

For worker threads opening the Realm instance at the beginning and closing it when exiting would be the most optimal:

new Thread(new Runnable() {
  public void run() {
    Realm realm = Realm.getDefaultInstance();
    doWork(realm);
    realm.close();
  }
}).start();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!