Realm taking too long to copy objects to RealmObject

南笙酒味 提交于 2020-01-06 19:29:12

问题


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

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