json与proto序列化,反序列化性能对比

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只包含数据体,没有{与: ,标签,结构更紧凑,更小.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值