Android Android bid farewell to SharedPreFerences, hello MMKV

Article Directory


Hello MMKV!

Insert picture description here

MMKV is Tencent's open-source lightweight persistent storage framework. Compared with the traditional SharedPreFerences (hereinafter referred to as SP), it has many advantages

  1. MMKV has a better locking mechanism to ensure the integrity of the data, and the SP's cross-process and apply mechanism will cause data loss
  2. SP is updated in full, and because of this, its time overhead is greater. MMKV storage is mmap, so full writing is not required
  3. MMKV can also directly import data in SP
  4. Using MMKV can better avoid program ANR
    ...

Why use MMKV

Using SP's low performance leads to program ANR, commit and apply may cause ANR, which is also one of the most hated diseases of Android engineers, so using MMKV can avoid this problem and make yourself feel comfortable! It can be seen from the figure below that the time-consuming comparison of reading and writing between MMKV and SP, MMKV is not inferior!

(The following picture is obtained from a code test written by myself)

I wrote a code test

MMKV Github gives:
Writing random int for 10000 times, we get this chart:
the chart obtained by writing random Int values ​​10000 times

MMKV Github Statistics Chart

Code usage

Let’s see how MMKV is resistant


Introduce

dependencies {
    implementation 'com.tencent:mmkv-static:1.2.9'
}

The simplest code chestnut

1. Initialize in Application

MMKV.initialize(this)//会返回MMVK存储的目录(String)

2. To create MMKV, you can create it through defaultMMKV(), which is the global default; you can also create it through mmkvWithID() corresponding to your own business, as follows:

val mmkv = MMKV.defaultMMKV()
val mmkv = MMKV.mmkvWithID("mmapID")

3. Data writing, Int, String, Boolean, Long, Float, Double type data can be written, only need to call encode() method to write the data, it will be overloaded according to the data type.

//写入Int
mmkv.encode("keyName1", 123)

//写入String
mmkv.encode("keyName2", "Text")

//写入Boolean
mmkv.encode("keyName3", true)

//写入Long
mmkv.encode("keyName4", 123L)

...

4. Data read, read through decode

//读取key为keyName1的Int类型数据
mmkv.decodeInt("keyName1")

//读取key为keyName1的Int类型数据,如果对应key的值不存在,会返回默认值123
mmkv.decodeInt("keyName1",123)

//读取key为keyName2的String类型数据,如果对应key的值不存在,会返回null,建议用下一个
mmkv.decodeString("keyName2")

//读取key为keyName2的String类型数据,如果对应key的值不存在,会返回默认字符串:defaultValue
mmkv.decodeString("keyName2", "defaultValue")

//不再举例,Boolean,Long,Float,Double参考以上使用


GitHub

MMKV: https://github.com/Tencent/MMKV