1

Here is the simple test code that I wrote to test compactRealm feature.

private void compactRealmTest(int count){
    Realm realm = Realm.getDefaultInstance();
    for(int i=0;i<count;++i) {
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                Person p = Person.getRandomPerson();
                realm.copyToRealm(p);
            }
        });
        final RealmResults<Person> personList = realm.where(Person.class).findAll();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                int size = personList.size();
                for(int i=0;i<size;++i){
                    personList.deleteFirstFromRealm();
                }
            }
        });
    }
    realm.close();
}

This function inserts an object and deletes that object from Realm immediately. After the end of this function,the realm db will not containt any objects. I observed that even though there were no objects after the execution of this function, the realm file size became ~4.5MB (after calling compactRealmTest(1000)). I decided to compact the realm by calling compactRealm() function. The file size was reduced from ~4.5MB to 3.5MB. Why is the Realm still using 3.5MB even though there are no objects in the realm?

Programmer
  • 51
  • 4

1 Answers1

0

Realm currently doesn't reclaim space on disk automatically, but will instead re-use the space when needed. This means that if you add the objects again, you shouldn't see an increase in file size either.

If you want to minimise the size of the file on on disk, you can use Realm.compactRealm(config) : https://realm.io/docs/java/latest/api/io/realm/Realm.html#compactRealm-io.realm.RealmConfiguration-

Christian Melchior
  • 19,978
  • 5
  • 62
  • 53