问题
I'm using realm to store a list of Products in my Andorid App. So, I receive a produtc's list with about 3k objects. And I'm trying to store them like this:
@Override
public void saveAll(List<ProductsDomain> domainProducts) throws InstantiationException, IllegalAccessException {
Realm instance = getRealmInstance();
RealmList<ProdutcsRealm> realmProducts = new RealmList<ProdutcsRealm>();
try {
ProdutcsRealm realmProduct = getClasseEntidadePersistencia().newInstance();
for (ProductsDomain domainProduct : domainProducts) {
fromDomainToPersistence(domainProduct, realmProduct);
realmProducts.add(realmProduct);
}
instance.beginTransaction();
instance.copyToRealm(realmProducts);// taking to long, 3k items
instance.commitTransaction();
} catch (Exception e) {
e.printStackTrace();
instance.cancelTransaction();
return;
}
}
So, the realm is taking too much time, something like 20 minutes. Anybody have any idea to get better performace?
Solved: I've found the problem! I was using the same ProductsRealm instance for all iteration. Looks like that Realm dont work well when you try to save a list of multiple references to de same object.
回答1:
It will be faster if you can add the objects to your Realm in fromDomainToPersistence(). The saveAll() method could be something like:
public void saveAll(...) {
Realm instance = getRealmInstance();
try {
instance.beginTransaction();
for (ProductsDomain domainProduct : domainProducts) {
fromDomainToPersistence(instance, domainProduct);
}
instance.commitTransaction();
} catch (Exception e) {
// ...
}
}
and
public void fromDomainToPersistence(Realm r, DomainProduct domainProduct) {
ProductRealm realmProduct = r.createObject(ProductRealm.class);
// set the fields' values
}
来源:https://stackoverflow.com/questions/31211192/realm-taking-too-long-to-copy-objects-to-realmobject