Mobile Database new King: Realm

Source: Internet
Author: User

Introduced

Realm is a cross-platform mobile database engine that supports iOS, OS X (Objective-c and Swift), and Android.

Released July 2014. The pioneering team, incubated by YCombinator, was the first database to be designed specifically for mobile platforms. The goal is to replace SQLite.

In order to completely solve the performance problem, the core data engine C + + build, not built on SQLite above the ORM. If you want to know more about the data engine implementation, you can view: Realm core Database Engine quest. So the benefits are much faster than the average ORM, even faster than a single, non-encapsulated SQLite.

Because it is ORM, it is also designed for mobile devices (IOS, Android), so it is very easy to use and the learning cost is low.

Rolling grade Performance

Data citation: Introducing-realm

Number of counts per second that can be queried in 200,000 data. Realm can make 30.9 queries per second after count.

One traversal query in 200,000, the data is similar to the previous count: Realm can traverse 200,000 data 31 times in a second, while CoreData can only make two queries.

This is the comparison of inserting data in a single transaction per second, realm can insert 94,000 records per second, in this comparison, pure SQLite performance Best, can insert 178,000 records per second. However, the Fmdb, which encapsulates SQLite, is probably half the realm.

Simple to use

is the instance code language objective? C.

Realm objects are not much different from other objects, just need to inherit Rlmobject

@interface Dog : RLMObject @property NSString *name; @property NSInteger age; @end Dog *mydog = [[Dog alloc] init];

It is also very simple to store, get a DB instance, write in a transaction.

RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^{      [realm addObject:mydog]; }];

Convenient query, you can query the results of a query. The conditions of the query are rich in support.

RLMResults *r = [Dog objectsWhere:@ "age > 8" ]; // Queries are chainable r = [r objectsWhere:@ "name contains ‘Rex‘ AND  name BEGINSWITH ‘大‘" ];

Zero-copy and lazy Loading

In the usual database, the data spends most of the time quietly on the hard drive. When you access a property in the Nsmanagedobject object, Core Data translates the request into a set of SQL statements, creates a database connection if the database is not connected, then sends the SQL statement to the hard disk, performs the retrieval, Read all the data from the matching search results and put them in memory (that is, memory allocation). However, at this point you need to deserialize the format (deserialize) because the format stored on the hard disk cannot be used directly in memory, which means that you need to adjust the bit so that the CPU can handle it.

However, realm skips the entire process of copying data into memory, called Zero-copy. This is done because the file is always memory-mapped, and you can access any content of the file, whether it is in memory or not. The important thing about the core file format is to make sure that the file format on the hard disk is memory-readable, so there is no need to perform any deserialization operations.

This brings up a problem, is the data all loaded into memory? So lazy loading comes into being, for example, after querying a set of data, you actually load it only when you actually access the object.

VS SQLite

The first version of SQLite was released in 2000 and is now 16 years old. In today's perspective, its programming abstraction is very low. We actually only want to put these objects in the business, can be queried out.

Even if it is already a packaged fmdb, it is still hard to write code like this:

FMDatabase *db = [FMDatabase databaseWithPath:@ "/tmp/tmp.db" ]; if  (![db open]) { [db release]; return ; } NSString *sql = @ "create table bulktest1 (id integer primary key autoincrement, x text);" "create table bulktest2 (id integer primary key autoincrement, y text);" "create table bulktest3 (id integer primary key autoincrement, z text);" "insert into bulktest1 (x) values (‘XXX‘);" "insert into bulktest2 (y) values (‘YYY‘);" "insert into bulktest3 (z) values (‘ZZZ‘);" ; success = [db executeStatements:sql]; sql = @ "select count(*) as count from bulktest1;" "select count(*) as count from bulktest2;"
"select count(*) as count from bulktest3;" ; success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) { NSInteger count = [dictionary[@ "count" ] integerValue]; XCTAssertEqual(count, 1, @ "expected one record for dictionary %@" , dictionary); return  0; < c18/> [db close];

VS CoreData

A detailed comparison is recommended in this article: CoreData VS Realm.

A comparison of a query is given below:

// Core Data let fetchRequest = NSFetchRequest(entityName:  "Specimen" ) let predicate = NSPredicate(format:  "name BEGINSWITH [c]%@" , searchString) fetchRequest.predicate = predicate let sortDescriptor = NSSortDescriptor(key:  "name" , ascending:  true ) fetchRequest.sortDescriptors = [sortDescriptor] let error = NSError() let results = managedObjectContext?.executeFetchRequest(fetchRequest, error:&error)

Realm is a lot simpler:

// Realm let predicate = NSPredicate(format:  "name BEGINSWITH [c]%@" , searchString); let specimens = Specimen.objectsWithPredicate(predicate).arraySortedByProperty( "name" , ascending:  true )

Summarize the benefits of realm for CoreData:

    • No need for architecture context that annoying thing

    • CoreData is a profound technology, do not want to be in a few days can be used very slip.

Don't look at the books.

    • Support Nspredicate

It's not too much to turn around from CoreData.

    • CoreData Multiple persistent files is a hassle, realm easily supports this feature

Disadvantage:

is to increase the volume of the application about 1MB. CoreData native support, does not increase app volume.

It looks great, but is this new?

Most of Realm's source code is open on GitHub: Realm. In less than two years, the project has received a lot of attention from the open source community:

Officials are also committed to continuing to address the various issues of user feedback. Or they can go straight to their Twitter.

Even if it is, is someone else using it?

Recommended reading this blog, the author describes his painful decision to abandon CoreData, how to safely migrate to realm: "Freeway change tires-for the legacy system replacement Database" (Paper/Jelly knife, Jane book author).

Many years ago, people made a decision to use CoreData to do local storage and replace Nsuserdefaults. The history of this is far from being tested, but since I joined the project, the entire team has been plagued by its high learning curve, complex data migration processes, and outdated and obsolete designs. So we decided to replace CoreData.

Let's look at the situation of so:

Already have about 20,000 related results, you are not a person!

Some questions to be aware of

    • In fact, I think these are acceptable questions. Technology is often a trade-off, and in order to achieve something, you always sacrifice something.

All storage objects need to inherit Realmobject

For example, my current project data from the network request back will inherit their own write a convenient parsing base class, here need to make some adaptation.

However, the problem does not exist in Swift. Because Swift is inherently a protocol-oriented programming paradigm.

    • Cannot customize Getter, setter

Realm will automatically generate getter, setter, if the custom getter, setter storage will have an impact. If you want to circumvent this problem, you can set this object's Ignore property.

For example, there is a property ID that requires a custom setter. You can set the ID to ignore attributes in the object's properties so that realm does not automatically generate getter, setter for it, but does not store the ID in the database. Next, customize a property for storage such as realm_id. The value can also be assigned to realm_id in the setter of the ID.

This problem also does not exist in swift, because Swfit uses the notification mechanism of Willset and Didset.

    • The result of the query is not an array

To enable chained queries that support query results, realm customizes a collection type. Can enumerate, but is not familiar with the array anymore. Because of the lazy loading mechanism of realm, it is not recommended to turn this enumeration into an array type at the data layer. The disadvantage is that the upper layer knows the storage logic of the data. Strictly speaking, we should not let the upper level know. But this design may be to facilitate the retrieval of the upper layer, realm has superior query performance.

Mobile Database new King: Realm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.