Protobuf对比XML、Json等其余序列化的优点java
protobuf | jackson | xstream | Serializable | hessian2 | hessian2压缩 | hessian1 | |
序列化(单位ns) | 1154 | 5421 | 92406 | 10189 | 26794 | 100766 | 29027 |
反序列化(单位ns) | 1334 | 8743 | 117329 | 64027 | 37871 | 188432 | 37596 |
bytes | 97 | 311 | 664 | 824 | 374 | 283 | 495 |
准备环境:python
1,Python版本3.5.4git
2,Protobuf版本3.7.0github
3,Protobuf安装包:protoc-3.7.0-rc1-win64.zipjson
4,Win10 64位系统 性能
步骤:测试
【下载protoc】ui
https://github.com/google/protobuf/releasesgoogle
根据本身的平台下载对应的编译器,个人是win10-64位,因此下载 protoc-3.7.0-rc1-win64.zipspa
设置环境变量:这一步使你在本地任何地方使用protoc这个指令
(右击“此电脑”。。。)
测试protoc:
新打开一个命令行:输入protoc --version,若是将输出版本号,说明protoc安装好了
【编写.proto协议文件】
新建一个protobuf文件夹,手动建立test2.proto文件:
并在test2.proto中输入:
syntax = "proto2";
message testinfo
{
required int32 devtype = 1;
required int32 devid = 2;
required int32 unitid = 3;
required int32 chlid = 4;
optional int32 testid = 5 [default = 0];
required bytes stepdata = 6;
}
【编译】:
打开命令行,切换到protobuf文件夹下下面,执行protoc --python_out=./ test2.proto
而后会生成一个python文件
在目录下新建文件 test.py,写入代码
import test2_pb2 testinfo = test2_pb2.testinfo() testinfo.devtype = 100 testinfo.devid = 2 testinfo.unitid = 3 testinfo.chlid = 4 testinfo.testid = 250 testinfo.stepdata = b'abd' print(testinfo, testinfo.devtype) # 打印 protobuf 结构的内容 out = testinfo.SerializeToString() print(out) # 打印 Protobuf 序列字符串 decode = test2_pb2.testinfo() decode.ParseFromString(out) print(decode) # 打印 解析Protobuf后的内容
运行python代码,获得如下结果,证实实验成功!