浅析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的基本数据类型及修饰符
protobuf支持的数据类型
数据类型 | 相关信息 |
---|---|
double | |
float | |
int32 | 使用可变长编码,编码负数时效率低,如果字段可能为负,则应该使用sint32 |
int64 | 使用可变长编码,编码负数时效率低,如果字段可能为负,则应该使用sint64 |
uint32 | 使用可变长编码 |
uint64 | 使用可变长编码 |
sint32 | 使用可变长编码,编码负数时效率比int32高 |
sint64 | 使用可变长编码,编码负数时效率比int64高 |
fixed32 | 总是占用4个字节,当字段的值大于228时效率比uint32高 |
fixed64 | 总是占用8个字节,当字段的值大于256时效率比uint64高 |
sfixed32 | 总是占用4个字节 |
sfixed64 | 总是占用8个字节 |
bool | |
string | string字段的值必须是UTF-8编码或7bit ASCII编码的文本 |
bytes | 可以包含任意字节序列 |
修饰符