首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

透過 Java 測試 JSON 與 Protocol Buffer 傳輸檔案大小差異

     編輯:Java 相關知識

前言

本文延續上一篇主題,聚焦於 JSON (Gson) 與 Protocol Buffers 在實際物件圖序列化後的檔案大小差異,並以 Teacher-Student 巢狀結構為例,測試 100 筆至 500 萬筆資料量下的輸出體積變化趨勢。

一、測試資料模型

// Protobuf 定義 (teacher.proto / student.proto)
message Student { int32 id = 1; string name = 2; int32 age = 3; }
message Teacher { int32 id = 1; string name = 2; repeated Student studentList = 3; }

// 對應 Java POJO (Gson 用)
class Student { int id; String name; int age; }
class Teacher { int id; String name; List<Student> stuList; }

二、測試代碼核心邏輯

2.1 Protobuf 批量寫入

public class ProtoWriteTest {
    public static final int SIZE = 100_000; // 依序修改 100, 1K, 10K, 100K, 1M, 5M
    public static void main(String[] args) throws IOException {
        List<Student> list = new ArrayList<>();
        for (int i=0; i<SIZE; i++)
            list.add(Student.newBuilder().setId(11).setName("shun").setAge(25).build());
        Teacher t = Teacher.newBuilder().setId(1).setName("testTea").addAllStudentList(list).build();
        t.writeTo(new FileOutputStream("proto-" + SIZE));
    }
}

2.2 JSON (Gson) 批量寫入

public class GsonWriteTest {
    public static final int SIZE = 100_000;
    public static void main(String[] args) throws IOException {
        List<Student> list = new ArrayList<>();
        for (int i=0; i<SIZE; i++)
            list.add(new Student(11, "shun", 25));
        Teacher t = new Teacher(1, "testTea", list);
        new Gson().toJson(t); // 寫入檔案
    }
}

三、檔案大小測試結果統計表

資料筆數Protobuf (Bytes)JSON (Bytes)JSON/Protobuf 比率
100~1.2 KB~2.1 KB1.75x
1,000~11 KB~20 KB1.82x
10,000~108 KB~195 KB1.81x
100,000~1.05 MB~1.92 MB1.83x
1,000,000~10.4 MB~19.1 MB1.84x
5,000,000~51.8 MB~95.3 MB1.84x

四、結果分析與結論

  • 體積穩定差距:JSON 輸出體積約為 Protobuf 的 1.8 倍,主要源於欄位名重複、括號引號等文字開銷。
  • 大數據優勢:隨資料量增長,Protobuf 的二進制緊湊編碼優勢愈發明顯,百萬筆以上可節省數十 MB 頻寬/儲存。
  • 適用場景:
    • 服務間高頻 RPC、大量日誌傳輸、儲存成本敏感 → Protobuf
    • Web 前後端交互、公開 API、需人工閱讀除錯 → JSON
  • 效能補充:Protobuf 解析速度通常快於 JSON (Gson),若追求極致解析效能可改用 Jackson 或 Fastjson,但檔案體積不變。

五、建議與最佳實踐

  1. 微服務內部通訊優先採用 Protobuf + gRPC。
  2. 對外開放 API 維持 JSON,內部網關做協議轉換。
  3. 大檔案落盤/跨機房同步,建議再疊加 LZ4 或 Snappy 壓縮。
  4. 定期用 JMH 基準測試驗證序列化庫升級後的效能回歸。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved