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?