Protobuf 和 JSON对比分析

3,787 阅读2分钟

Protocol Buffers (a.k.a., protobuf) are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data.

Protobuf是Google公司开发的一种语言中立 平台中立 可扩展 的 对结构化数据 序列化的机制。

本文主要对Protobuf和JSON序列化&反序列化的性能做横向对比分析。 JSON序列化使用Google官方的Gson框架。

ProtobufGsonLanguagePlatform
3.17.32.8.7KotlinmacOS IntelliJ IDEA

测试序列化内容,高效作业25分钟的训练数据(mock)

数据结构

syntax = "proto3";
package me.sunnyxibei.data;
option java_package = "me.sunnyxibei.data";
option java_outer_classname = "TaskProto";

message  Eeg{
  repeated double  alphaData = 1;
  repeated double  betaData = 2;
  repeated double  attentionData = 3;
  repeated int64  timestampData = 4;
  int64  startTimestamp = 5;
  int64  endTimestamp = 6;
}
message TaskRecord{
  string localId = 1;
  int64  localCreated = 2;
  int64  localUpdated = 3;
  int32 score = 4;
  int64  originDuration = 5;
  string  subject = 6;
  string  content = 7;
  Eeg eeg = 8;
}

对比结果 repeat = 1

Gson序列化大小 = 30518 bytes
Gson序列化时间 = 113 ms
protobuf序列化大小 = 13590 bytes
protobuf序列化时间 = 39 ms
*************************
Gson反序列化时间 = 15 ms
protobuf反序列化时间 = 3 ms

repeat = 10

Gson序列化时间 = 137 ms
protobuf序列化时间 = 41 ms
*************************
Gson反序列化时间 = 50 ms
protobuf反序列化时间 = 5 ms

repeat = 100

Gson序列化时间 = 347 ms
protobuf序列化时间 = 47 ms
*************************
Gson反序列化时间 = 212 ms
protobuf反序列化时间 = 22 ms

repeat = 1000

Gson序列化时间 = 984 ms
protobuf序列化时间 = 97 ms
*************************
Gson反序列化时间 = 817 ms
protobuf反序列化时间 = 105 ms

repeat = 10000

Gson序列化时间 = 7034 ms
protobuf序列化时间 = 225 ms
*************************
Gson反序列化时间 = 5544 ms
protobuf反序列化时间 = 300 ms

repeat = 100000

Gson序列化时间 = 65560 ms
protobuf序列化时间 = 1469 ms
*************************
Gson反序列化时间 = 49984 ms
protobuf反序列化时间 = 2409 ms

结论:

  1. 空间对比,Protobuf序列化后的数据大小,为JSON序列化后的44.5%
  2. 时间对比
次数序列化(Protobuf/JSON)反序列化(Protobuf/JSON)
134.5%20%
1029.9%10%
10013.5%9.43%
10009.9%12.9%
100003.2%5.41%
1000002.24%4.82%