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


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

The simplest code chestnut

1. Initialize in Application


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.

mmkv.encode("keyName1", 123)

mmkv.encode("keyName2", "Text")

mmkv.encode("keyName3", true)

mmkv.encode("keyName4", 123L)


4. Data read, read through decode




mmkv.decodeString("keyName2", "defaultValue")