概述
在目前客户端开发中, PB 格式已经是网络传输的序列化/反序列化方案的标配。但 PB 同时对我们 native 开发中的缓存实现也是有很大价值的。
缓存方案对比
本人对比了如下几种客户端的缓存方案:
- PB + DiskLruCache
- Ormlite/Sqlite
- Gson + DiskLruCache
其中 PB + DiskLruCache 方案与 Gson + DiskLruCache 方案的性能对比如下:
07-25 16:51:51.319 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json write consume=35
07-25 16:51:51.429 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json read consume=110
07-25 16:51:51.439 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb write consume=10
07-25 16:51:51.489 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb read consume=45
07-25 16:52:11.229 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json write consume=29
07-25 16:52:11.319 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json read consume=87
07-25 16:52:11.319 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb write consume=5
07-25 16:52:11.329 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb read consume=6
07-25 16:53:46.259 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json write consume=36
07-25 16:53:46.329 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json read consume=72
07-25 16:53:46.339 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb write consume=5
07-25 16:53:46.339 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb read consume=5
07-25 16:54:14.159 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json write consume=39
07-25 16:54:14.249 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] json read consume=85
07-25 16:54:14.249 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb write consume=5
07-25 16:54:14.259 28287-28287/com.eg.android.AlipayGphone D/HomePresenter: [28287:main] pb read consume=5
实测数据:
json write | pb write | json read | pb read |
---|---|---|---|
35 | 10 | 110 | 45 |
29 | 5 | 87 | 6 |
36 | 5 | 72 | 5 |
39 | 5 | 85 | 5 |
分项加总后:
json write | pb write | json read | pb read |
---|---|---|---|
139 | 25 | 354 | 61 |
可以看出写操作,pb 所花时间仅占 json 的18%;读操作,pb 所花时间仅占 json 的17%。此外,OrmLite/Sqlite 在性能方面与 json 相当。
使用 PB 缓存的正确姿势
既然好处是明显的,我们看下如何应用这项新技巧,直接上代码:
QueryCommunityResp queryCommunityResp = ...; // 目标继承自 Message 的PB model 的实例
queryCommunityResp.toByteArray(); // 序列化
final Wire wire = new Wire();
try {
QueryCommunityResp newResp = wire.parseFrom(queryCommunityResp.toByteArray(),
QueryCommunityResp.class); // 反序列化
} catch (IOException e) {
// TODO: handle exception
}
别忘了添加 api 包依赖:
<dependency>
<groupId>com.alipay.android.phone.thirdparty</groupId>
<artifactId>wire-api</artifactId>
<version>1.5.3</version>
<scope>provided</scope>
</dependency>