Edit recommendation: Rare earth Nuggets, this is an application for technical developers, you can get the latest and best quality technology nuggets, not only Android knowledge, front-end, back-end as well as products and design dabbler, want to become a friend of full stack engineers do not miss it!

原文 : Realm, ObjectBox or Room. Which one is for you?

Choose, choose, choose. Android developers have a plethora of libraries to choose from when it comes to data storage. There are tools available for both object maps and data sets. Some are out-of-the-box, such as Shared Preferences and pure SQL, while others require external dependencies. Rest assured, I’m not going to talk about writing complex data queries. Instead, I’ll compare a few top-tier libraries: the newly released Room Persistence Library, the somewhat old Realm, and the lesser-known ObjectBox, a Library that recently went out of beta.

I’ll leave the final choice to you, but who comes first should be pretty clear at the end of the article. Before we do that, let’s go through them one by one.

Realm 

Since its creation (circa 2011, originally called “TightDB”), Realm has been the Realm of choice for many developers. Why is that? Simplicity (using almost standard Java objects), speed (mostly written in C++), and no SQL. Creating a Realm database is simple, as is using it. This library requires very little setup, and the documentation on the official website explains it in detail:

The first thing you need is a model that represents the stored object:

open class Box (
@PrimaryKey var size: Long = 0, 
var name: String = "", 
@Ignore var tempReference: Int = 0) : RealmObject() {}Copy the code

The only thing worth mentioning is that if you use Kotlin, all members must have default values. Annotations and inheriting RealmObject this is all pretty straightforward, so let’s move on.

Realm of use:

Realm.init(context)
val realm = Realm.getDefaultInstance()Copy the code
val box = realm.where(Box::class.java).findFirst()
realm.executeTransaction {
//modifying an exsiting object
 box.size = 20
 box.name = "John"Copy the code
//creating a new object
 val secondBox = realm.createObject(Box::class.java)
 secondBox.size = 30
}Copy the code

Full example

Room Persistence Library 

Room is Google’s newest and brightest library, and has a central place in the official architecture guide. Room provides an abstraction layer on top of SQLite, making it easy to access databases while taking full advantage of SQLite’s capabilities. It encapsulates SQL and exposes easy-to-understand Java methods to developers. Remember I said there were no SQL queries? Okay, now I’m ready to write some queries, but don’t worry, Room provides some security mechanisms that warn you of serious errors.

Since Room has become more popular, I will try to make a brief introduction to it.

Room has three main components, all of which are annotated:

Database: You can use it to create a Database. This annotation defines the list of entities and the Data Access Objects (DAOs) in the database. It is also the entry point for the underlying database.

The annotation class must be an abstract class that inherits RoomDatabase. You can use the Room. DatabaseBuilder () or Room. InMemoryDatabaseBuilder () to instantiate it.

Entity: This component represents a table in the database. For each entity, the database creates a table to hold. You must refer to the Entity class in the Entity array of the Database class.

DAO: This component represents the Data Access Object class or interface. The DAO is responsible for defining the methods to manipulate the database. The @DATABASE annotation class must include an abstract method that returns the @DAO class with an argument of 0.

Here is the building code that implements the mentioned code (shamelessly copied from this article) :

@entity (tableName = "task") Data Class task (@columnInfo (name = "Completed_flag") var completed: Boolean = false, @columninfo (name = "task_desciption") var description: String) {@columnInfo (name = "ID") @primaryKey (autoGenerate = true) var ID: Long = 0} @dao interface TaskDao {@query (" select * from task ") fun getAllTasks(): List<Task> @query (" select * from Task where id = :p0 ") fun findTaskById(id: Long): Task @Insert(onConflict = REPLACE) fun insertTask(task: Task) @Delete fun deleteTask(task: Task) } @Database(entities = arrayOf(Task::class), version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun taskDao(): TaskDao }Copy the code

Creating a database and calling it is as simple as this:

Var database = room.databaseBuilder (context, AppDatabase::class.java," Db ").allowMainThreadqueries ().build() database.taskdao ().inserttask (Task(description = "simple! ))Copy the code

ObjectBox 

As the newest member, ObjectBox brings a lot to the table. But with the bar set high, does this new NoSQL technology stack up to previous war veterans? If it wants to stand up to Realm and Room, it will have to land a hammer. And it wasn’t just a hit, it was a set. Here are its typical highlights:

  • Speed: Like Realm, ObjectBox provides excellent performance, sometimes exceeding it.

  • QueryBuilder: ObjectBox simply asks you to query the object and check it at compile time.

  • Object Relations: Object references / relationships are a built-in type; they are native references

  • No manual migration required: Upgrades are completely automatic, with no concern for attribute changes or naming changes

  • More and more

So what does it look like in practice?

Model is a must:

@Entity
data class Note (
 @Id var id: Long = 0,
 val text: String
)Copy the code

An ObjectBox stores its data in things called Boxes. To use ObjectBox to manage your database, you need only take two steps:

A “Box Store” object, initialized in the Application:

MyObjectBox.builder().androidContext(App.this).build()Copy the code

And Boxes for each model. These boxes are responsible for the interaction with the database.

var notesBox = boxStore.boxFor(Note::class.java)Copy the code

One important detail is that these Box types are automatically generated, so there’s no extra worry!

Once you’re done, you’re ready to use it. Here are some ways to do it:

notesBox.put(note)
notesBox.remove(note)
notesBox.count()Copy the code

To see all of Box Class’s methods, see its JavaDoc. Note here that a compatibility layer called DaoCompat allows ObjectBox to use a Greendao-like API.

To compare

So far, all the libraries have done pretty much the same thing, some using SQL, some not. But what’s interesting to us are the differences. In the figure below, we tested the performance of three methods using an open source ranking app.

That’s an interesting result, right? The test results clearly show that most of the time, ObjectBox overwhelms all comparisons. And as the test data grew, the gap widened!

Queries also seem to be one of ObjectBox’s strengths. The tests focus on indexes and strings, and the results are obvious.

What about the APK size? How much will each of these libraries burden the project? We can use the newly released APK Analyzer to see just how big each one is.

ObjectBox and Realm take up 1 — 1.5MB and 3 — 4MB, respectively (depending on the phone’s architecture), while Room, as an SQL wrapper, takes up only about 50kb. But as loyal Android developers, we also have to abide by the annoying method count limit. Here again, Room seems to be ahead, with only 300 methods. ObjectBox and Realm are 1300 and 2000 methods, respectively.

Functionally, each library provides its own additional functionality. Room adds more than just everything SQLite can do. Such as a fully testable migration mechanism. ObjectBox, on the other hand, does not, as it handles most of the migration itself (although some changes require additional work). Realm offers the most functionality, including custom configurations, encryption, and more (one reason for its size).

conclusion

You can see that whichever you choose has its pros and cons. If you’re looking for speed and efficiency, the obvious choice is ObjectBox. However, if you are limited by app size, the number of methods is approaching the limit of 64K, and you are willing to handle SQL, Room may be the solution for you. Realm, while not the fastest, nor the smallest, with seven years of debugging and refinement behind it, offers the most stable, least buggy and most robust solution.

I’ll leave the answer to you, but remember that your app is only as good as your choices (and the quality of your code, but that’s another topic).