What is the most efficient way to store long list of Objects in Realm?

寵の児 提交于 2019-11-28 08:31:16

Your original solution saves 10000 objects in 10000 transactions and creates 10000 objects for it, so that's pretty much the worst possible approach.


Technically the right way should be this:

public void storeBookings(final List<Booking> bookings) {
    mRealm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.insertOrUpdate(bookings);
        }
    });
}

In most cases when the saved object is not the same as the original object, what I do is this:

public void storeBookings(final List<Booking> bookings) {
    mRealm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmBook realmBook = new RealmBook();
            for(Booking booking : bookings) {
                realmBook = mapper.toRealm(booking, realmBook); // does not create new instance
                realm.insertOrUpdate(realmBook);
            }
        }
    });
}

This solution uses 1 detached object to map the content of the list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!