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代碼,獲得如下結果,證實實驗成功!