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

后端 未结 1 1124
栀梦
栀梦 2020-12-09 11:35

I\'m trying to compare Realm with Snappydb (This is my repo for those who would like to have a look at benchmark). I guess my way is wrong,

相关标签:
1条回答
  • 2020-12-09 12:05

    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.

    0 讨论(0)
提交回复
热议问题