Search code examples
androidrealm

How to add 1 milion items in Realm correctly?


I want to choose between native SQLiteDatabase and Realm to deal with a big amount of data.

For benchmark I add to storage 1 milion of Product entities:

{id:integer,sku:string,name:string,data_creating:string}

Using SQLiteDatabase it takes near 1 minute 34 seconds on my device.

Using Realm it takes more them 10 minutes.

My code is:

Realm realm = Realm.getInstance(getApplicationContext());
realm.beginTransaction();
for(int i = 0 ; i < 1000000;i++){
    Product product = realm.createObject(Product.class);
    product.setId(i+1);
    product.setName("Product_"+i);
    product.setSku("SKU__"+i);
    product.setDateCreated(new Date());
}
realm.commitTransaction();

How can I improve my code for better time performance?


Solution

  • You have to be aware that SQLite and Realm are two very different things. Realm is an object store and you are creating a lot of objects in the code shown above. Depending on your model class and the number of rows/objects, you will often see that Realm is a bit slower on inserts. To do a fair comparison, you could compare Realm with one of the many excellent ORMs out there.

    Said that, Realm offers a low-level interface (io.realm.internal). I wouldn't recommend you to use it as it is currently undocumented. Your example would look like this:

    long numberOfObjects = 1000000;
    SharedGroup sharedGroup = new SharedGroup("default.realm");            
    WriteTransaction writeTransaction = sharedGroup.beginWrite();
    Table table = writeTransaction.getTable("class_Product");
    table.addEmptyRows(numberOfObjects);
    for (int i = 0; i < numberOfObjects; i++) {
        table.setLong(0, i, i);              // id
        table.setString(1, i, "Product_"+i); // name
        table.setString(2, i, "SKU__"+i);    // sku
        table.SetDate(3, i, new Date());     // date
    }
    writeTransaction.commit();
    sharedGroup.close();
    

    You can now compare two table/row oriented data stores, and you will probably find that Realm is a bit faster than SQLite.

    At Realm, we have a few ideas on how to get our object interface to run faster, and we hope to be able to implement them in the near future.