之前写过使用Protobuf的文章,参考链接
https://blog.csdn.net/zhtttyyzc/article/details/88554911
微信mmkv轻量级存储也用到Protobuf
那么Protobuf跟传统的json有哪些优势,又有哪些缺点呢
https://developers.google.com/protocol-buffers/docs/encoding
https://github.com/google/leveldb/blob/master/util/coding.cc
其实里面说的非常清楚,这里就简单的来说说
java中一个 int = 4个字节 = 4byte 1byte=8bit 俗称大B小b
150用2进制表示
0000 0000 0000 0000 0000 0000 1001 0110
都为0的话 先省略 好看点 留最后2字节
0000 0000 1001 0110
然后从右到左 每7位 插入msb标志 1表示还属于这个数字 往下继续识别 0则这个数字读取完了
因为Protobuf的算法是会让字节反转的 那么在反转前 插入msb
从右到左首先发现1 再插入msb数字1 那本身的1往前挪
00 0000 0001 1001 0110
去掉前面的0 反转 就生成了最终Protobuf传输的数据
1001 0110 0000 0001
再看文档上面150的解析
96 01 = 1001 0110 0000 0001
→ 000 0001 ++ 001 0110 (drop the msb and reverse the groups of 7 bits)
→ 10010110
→ 128 + 16 + 4 + 2 = 150
这个int 150数字 用json传递 需要传递4个字节 但是pb只需要传递2个字节 效率快了一倍
如果int为1的话 二进制是0001 只需要传递1个字节 速度快了3倍
但是通过上面也知道pb比json多了一个步骤,解析字节
取舍看自己了