在微服務架構與高效能系統中,資料序列化格式的選擇直接影響網路傳輸頻寬與解析速度。本文實測比較 Protocol Buffers (Protobuf) 與 JSON (Gson) 在不同資料量下的序列化體積、壓縮耗時與吞吐量,並附上完整基準測試代碼,幫助開發者依據場景做最佳選型。
| 格式 / 等級 | 體積 (Bytes) | 壓縮率 vs 原始 |
|---|---|---|
| 原始檔案 | 354,509,602 | 100% |
| GZIP | 64,200,201 | 18.1% |
| Deflate Level 1 | 78,369,711 | 22.1% |
| Deflate Level 6 | 64,200,191 | 18.1% |
| Deflate Level 9 | 63,839,200 | 18.0% |
| Snappy (normal) | 138,250,196 | 39.0% |
| Snappy (framed) | 101,470,113 | 28.6% |
| LZ4 (fast) | 98,316,501 | 27.7% |
| LZ4 (high) | 82,076,909 | 23.1% |
| Protobuf (未壓縮) | ~60-80 MB 區間 | 視結構而定 |
結論:Protobuf 二進制編碼天生體積遠小於 JSON 文字格式;若再搭配 LZ4/Deflate 壓縮,體積優勢更明顯。
| 實作 | 耗時 (ms) | 吞吐量 (MB/s) | 輸出體積 (MB) |
|---|---|---|---|
| LZ4 Fast (JNI) | 1,056 | 320 | 93.8 |
| Snappy (normal) | 2,201 | 154 | 131.8 |
| Deflate Level 1 | 4,523 | 75 | 74.7 |
| GZIP (≈Deflate L6) | 10,352 | 33 | 61.2 |
| LZ4 High (JNI) | 7,490 | 45 | 78.3 |
| Deflate Level 9 | 14,878 | 23 | 60.9 |
關鍵發現:
// 寫入
Teacher.Builder tea = Teacher.newBuilder().setId(1).setName("testTea");
for (int i=0; i<SIZE; i++) {
tea.addStudentList(Student.newBuilder().setId(11).setName("shun").setAge(25).build());
}
tea.build().writeTo(new FileOutputStream("proto-" + SIZE));
// 讀取
Teacher t = Teacher.parseFrom(new FileInputStream("proto-" + SIZE));
Teacher teacher = new Teacher();
teacher.setStuList(stuList); // List<Student>
new Gson().toJson(teacher); // 輸出字串再寫檔
完整 JMH 基準測試代碼、.proto 定義、Maven 專案結構請參考文末附件或專案倉庫。