1 protobuf/xml/json 对比
从数据的存储格式的角度进行对比
假如要存储一个键值对:
{price:150}
1.1 protobuf 的表示方式
- message Test {
- optional int32 price = 1;
- }
protobuf 的物理存储: 08 96 01, 就 3 个字节.
采用 key-value 的方式存放, 第一个字节是 key, 它是 field_number <<3 | wire_type 构成.
所以 field number 是 1,wire type 是 0, 即 varint, 有了这个 wire type 就可以用来解析 96 01 了.
96 01 = 1001 0110 0000 0001
即 001 0110 000 0001
- least significant first
- 1001 0110 = 128 + 16 + 4 + 2 = 150.
只要 3 bytes
1.2 xml 的存储表示
- <some>
- <name>price</name>
- <value>150</value>
- </some>
大约要 36 bytes
1.3 json 的存储表示
{price:150}
大约 11bytes
比较可见相比于 json 和 xml,protobuf 对象序列化时可以节省非常大的空间, 从而带来非常快的传输速度.
另外由于 protobuf 表示简单, 解析速度也更快.
参考
1 https://developers.google.com/protocol-buffers/docs/encoding
来源: http://www.bubuko.com/infodetail-2629959.html