说了这么久,Protobuf到底是什么呢,借花献佛,引用Protobuf官网的解释:
Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs that are compiled against the “old” format.
本人英语水平有限,就在此简单翻译一下,大意是:
Protobuf是一种灵活高效可序列化的数据协议,相于XML,具有更快、更简单、更轻量级等特性。支持多种语言,只需定义好数据结构,利用Protobuf框架生成源代码,就可很轻松地实现数据结构的序列化和反序列化。一旦需求有变,可以更新数据结构,而不会影响已部署程序。
从上面我们可以总结出,Protobuf具有以下优点:
- 代码生成机制
syntax = “proto3”;
package me.ele.demo.protobuf;
option java_outer_classname = “LoginInfo”;
message Login {
string account = 1;
string password = 2;
}
这是一个用户登录信息的数据结构,通过Protobuf提供的Gradle Plugin就可以在me.ele.demo.protobuf
目录下编译自动生成LoginInfo类,并有序列化和反序列化等Api。
- 高效性
用千里眼项目中跑出来的数据进行对比,更具说服力。
序列化时间效率对比:
数据格式 | 1000条数据 | 5000条数据 |
---|---|---|
Protobuf | 195ms | 647ms |
Json | 515ms | 2293ms |
序列化空间效率对比:
数据格式 | 5000条数据 |
---|