用于结构化数据的序列化 高效
高效
- 性能优异
使用二进制编码进行数据序列化 比基于文本的xml json
更小 序列化和反序列化更快 - 内存占用低
可拓展性
- 前后兼容
添加新字段 不破坏现有代码
跨平台
- 支持多种语言
代码生成
使用.proto
定义数据结构
// varlist.proto begin
syntax = "proto3";
enum VarType {
None = 0;
Bool = 1;
Int32 = 2;
Int64 = 3;
Float = 4;
Double = 5;
Str = 6;
Bytes = 7;
}
/*
VarList:
A flexible data structure to store data with different types and arbitrary
amount. When the protocol changes, the VarList.proto is no need to change;
instead, the parsing algorithm should be changed to meet the new protocol.
The "types" and "indexes" are helper member to map data and it's type and
index in a VarList message; therefore, the information should be taking
care on our own.
*/
message VarList {
repeated bool bools = 1;
repeated double doubles = 2;
repeated float floats = 3;
repeated sint64 int64s = 4;
repeated int32 ints = 5;
repeated string strs = 6;
repeated VarType types = 7;
repeated bytes bytez = 8;
repeated int32 indexes = 9; // TODO: confusing, rename to "subindexes" might be better
int32 count = 10;
}
// varlist.proto end
repeated
是一个关键字 用于定义一个字段可以包含多个值的消息类型 可以高效地存储多个值 使数据格式更紧凑
为什么二进制编码比文本性能高?
- 空间效率
更加紧凑 不需要文本那样包含可读性字符 如空格 换行符等 - 解析速度
直接解析 二进制数据在解析时无需文本那样进行字符解析和转换 - 内存和CPU效率
少量分配 更少的内存分配和垃圾回收 可以直接读取内存中的数据对象 - 安全
防止误解析 文本解析可能收到字符集 编码格式问题的影响
flutter 如何集成?
https://pub.dev/packages/protoc_plugin