Go: App-side database (High performance) realm (iOS, Android support)

Source: Internet
Author: User

Ext.: http://ios.jobbole.com/85041/

Mobile Database new King: Realm

2016/05/14 · iOS Development · Database

share to:0 Original source: No story of the Zhuo classmate (@ No story of Zhuo students)

About Realm

Realm is a cross-platform mobile database engine that supports iOS, OS X (Objective). C and Swift) as well as 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.
To completely solve the performance problem, the core data engine is built in C + + and is not an ORM built on SQLite. 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

123456 @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.

12345 rlmrealm *realm Span class= "Crayon-o" >= [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.

1234 RLMResults *r = [Dog objectswhere:@"Age > 8"]; //Queries is chainabler = [R objectswhere:@"name contains ' Rex ' and name Beginswith ' big '"]< c12>;

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:

1234567891011121314151617181920212223242526 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< Span class= "crayon-h" > = [ dictionary[@ " Count "] integervalue ] xctassertequal(count, 1, @"expected one record for dictionary%@", c12> dictionary); return 0; }]; [db close];

VS CoreData

A detailed comparison is recommended in this article: CoreData VS Realm.
A comparison of a query is given below:

12345678 //Core Datalet 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:

Realm is a lot simpler:

123 //Realmlet 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 cumbersome, 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 the coredata, how to safely migrate to realm: "Freeway change tires-for legacy system replacement database."

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.

Paper/Jelly Knife (Jane book author)
Original link: http://www.jianshu.com/p/d684693f1d77
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.

Go: App-side database (High performance) realm (iOS, Android support)

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.