本文延續上一篇主題,聚焦於 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; }
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));
}
}
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 KB | 1.75x |
| 1,000 | ~11 KB | ~20 KB | 1.82x |
| 10,000 | ~108 KB | ~195 KB | 1.81x |
| 100,000 | ~1.05 MB | ~1.92 MB | 1.83x |
| 1,000,000 | ~10.4 MB | ~19.1 MB | 1.84x |
| 5,000,000 | ~51.8 MB | ~95.3 MB | 1.84x |