Android 领域:内存不足

Android Realm: Out of memory

使用循环次数超过3000次:

for (Element e2 : elinks2) {
    AllAuthors allauthor = new AllAuthors();
    allauthor.setUrl_base(href.substring(0, href.length() - 1));
    allauthor.setAuthor_fio(e2.text().trim());
    allauthor.setLetters(e.attr("href"));

    Realm realm_2 = null;
    try {
           realm_2 = Realm.getInstance(new File(func.getFolder("db")), getResources().getString(R.string.app_name_db) + ".realm");
           realm_2.beginTransaction();
           realm_2.copyToRealmOrUpdate(allauthor);
           realm_2.commitTransaction();
    } finally {
           if(realm_2 != null) {
               realm_2.close();
           }
    }
}

添加(或更新)大约 1000 条记录后出错

Out of memory in io_realm_internal_SharedGroup.cpp line 164

在线发誓

realm_2.commitTransaction();

有什么建议?

AllAuthors.class:

@RealmClass
public class AllAuthors extends RealmObject {

    @PrimaryKey
    private String url_base;

    private String author_fio;

    private String letters;

    ....Standard getters & setters generated....
}

您不断打开和关闭一个 Realm,同时进行大量小额交易。虽然该模式效率很低,但它本身不应该导致您 运行 内存不足。但是,如果您 运行 在后台线程中进行此操作,对于每个事务,Realm 都必须维护与原始数据的差异,直到所有线程上的 Realms 都可以更新(这发生在 Looper 事件或调用Realm.refresh())。我建议重构为以下内容,这样既更快又占用内存更少:

Realm realm_2 = Realm.getInstance(new File(func.getFolder("db")), getResources().getString(R.string.app_name_db) + ".realm");
realm_2.beginTransaction();
for (Element e2 : elinks2) {
    AllAuthors allauthor = new AllAuthors();
    allauthor.setUrl_base(href.substring(0, href.length() - 1));
    allauthor.setAuthor_fio(e2.text().trim());
    allauthor.setLetters(e.attr("href"));
    realm_2.copyToRealmOrUpdate(allauthor);
}
realm_2.commitTransaction();
realm_2.close();