1. 说proto快,必须知道他快多少?为什么快?
快多少?
// 测试proto序列化和反序列化的性能
func BenchmarkProtobufMarshal(b *testing.B) {
// 创建一个 Request 对象
req := &demo.Request{
Ping: "ping",
}
// 测试序列化的性能
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := proto.Marshal(req)
if err != nil {
b.Fatalf("Failed to marshal: %v", err)
}
}
//BenchmarkProtobufMarshal-8 26795323 46.30 ns/op 8 B/op 1 allocs/op
}
func BenchmarkProtobufUnmarshal(b *testing.B) {
// 创建一个 Request 对象并序列化
req := &demo.Request{
Ping: "ping",
}
data, err := proto.Marshal(req)
if err != nil {
b.Fatalf("Failed to marshal: %v", err)
}
// 测试反序列化的性能
b.ResetTimer()
for i := 0; i < b.N; i++ {
var res demo.Request
err := proto.Unmarshal(data, &res)
if err != nil {
b.Fatalf("Failed to unmarshal: %v", err)
}
}
//BenchmarkProtobufUnmarshal-8 14313553 74.55 ns/op 68 B/op 2 allocs/op
}
//测试json序列化和反序列化的性能
func BenchmarkJsonMarshal(b *testing.B) {
// 创建一个 Request 对象
req := &demo.Request{
Ping: "ping",
}
// 测试序列化的性能
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := json.Marshal(req)
if err != nil {
b.Fatalf("Failed to marshal: %v", err)
}
}
// BenchmarkJsonMarshal-8 13439467 80.96 ns/op 16 B/op 1 allocs/op
}
func BenchmarkJsonUnmarshal(b *testing.B) {
// 创建一个 Request 对象并序列化
req := &demo.Request{
Ping: "ping",
}
data, err := json.Marshal(req)
if err != nil {
b.Fatalf("Failed to marshal: %v", err)
}
// 测试反序列化的性能
b.ResetTimer()
for i := 0; i < b.N; i++ {
var res demo.Request
err := json.Unmarshal(data, &res)
if err != nil {
b.Fatalf("Failed to unmarshal: %v", err)
}
}
//BenchmarkJsonUnmarshal-8 3771028 311.5 ns/op 288 B/op 6 allocs/op
}
序列化
json: 13439467
proto: 26795323
proto快2倍左右
反序列化
json: 3771028
proto: 14313553
proto快4倍左右
有数据支撑比单独说快更具有说服力
为什么快?
json是通过标签将数据映射到对应的字段
proto是通过顺序直接填充值进去
相当于分发信封,一种是叫道名字的来取(json); 一种是所有人通过信封的顺序排好了对,一个个拿就可以了(proto).
而且proto只包含数据体,没有{与: ,标签,结构更紧凑,更小.