实习中学习一下 Protobuf 的功能和语法等,整理为此笔记。主要为翻译官方文档而来。
什么是 Protobuf
Protobuf 是 Google 公司研发的一种用于序列化结构数据的机制,全称为 Protocol Buffers,具有语言无关、平台无关以及可拓展的特性。
我们常常把 Protobuf 与 XML (Extensible Markup Language) 相比较,它们二者都被设计来传输和存储结构化数据。相比于 XML,Protobuf 有如下优势与缺点:
- Protobuf 占用的空间更小。Protobuf 采用二进制格式存储数据,适合网络传输和高性能场景;而 XML 采用文本格式存储数据,数据冗余度较高。
- Protobuf 编码和解码更快。测试 Protobuf 库和 tinyxml2 库执行序列化和反序列化操作(相关链接),Protobuf 序列化速度大约是 XML 的 5 - 9 倍,反序列化速度大约是 XML 的 9 - 12 倍,更加适合高性能场景。
- Protobuf 不具有可读性。Protobuf 传输的值为二进制数据,需要专用工具生成和解析;而 XML 自身的标签和文本内容具有一定的可读性。
使用 Protobuf,只需要编写 .proto
文件来描述需要传输和存储的结构数据,随后编译器会为之创建一个类,实现结构数据的自动编码和解码。
With protocol buffers, you write a .proto description of the data structure you wish to store. From that, the protocol buffer compiler creates a class that implements automatic encoding and parsing of the protocol buffer data with an efficient binary format. The generated class provides getters and setters for the fields that make up a protocol buffer and takes care of the details of reading and writing the protocol buffer as a unit.