1.MMKV简介
腾讯微信团队于2018年9月底宣布开源 MMKV ,这是基于 mmap 内存映射的 key-value 组件,底层序列化/反序列化使用 protobuf 实现,主打高性能和稳定性。近期也已移植到 Android 平台,一并对外开源。
MMKV 是基于 mmap 内存映射的 key-value 组件,底层序列化/反序列化使用 protobuf 实现,性能高,稳定性强。从 2015 年中至今,在 iOS 微信上使用已有近 3 年,其性能和稳定性经过了时间的验证。近期也已移植到 Android 平台,一并开源。
MMKV最新源码托管地址:https://github.com/Tencent/MMKV
这篇文章写得很详细了:https://www.jianshu.com/p/92bcb77f8eca
2.简单使用,其实去GitHub上Wiki就有全部得使用方法
gradle引用:implementation 'com.tencent:mmkv:1.0.18'
初始化:
//第一步;两种方式都可以
String initialize = MMKV.initialize(this);
// String initialize = MMKV.initialize(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/app/");//指定想要存储得路径
//第二步
MMKV preferences = MMKV.defaultMMKV();
使用也很简单:
mmkv.encode("a", 10); mmkv.encode("b", 100);
再来看看怎么迁移SharedPreferences:
SharedPreferences sp = getSharedPreferences("a", MODE_PRIVATE);
for (int i = 0; i < 100; i++){
sp.edit().putInt(""+i, i).commit();
}
MMKV.initialize(this);
MMKV preferences = MMKV.defaultMMKV();
preferences.importFromSharedPreferences(sp);
// just use it as before像以前一样使用
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("bool", true);
editor.putInt("int", Integer.MIN_VALUE);
editor.putLong("long", Long.MAX_VALUE);
editor.putFloat("float", -3.14f);
editor.putString("string", "hello, imported");
HashSet<String> set = new HashSet<String>();
set.add("W"); set.add("e"); set.add("C"); set.add("h"); set.add("a");
editor.putStringSet("string-set", set);
// commit() is not needed any more
//editor.commit();不需要提交了
System.out.println("keys:"+ Arrays.toString(preferences.allKeys()));
这样得话,我们从SharedPreferences迁移到MMKV得时候,只需要在初始化得地方改两行代码即可;以前写的存储代码都不用管。