背景
golang中json序列化和反序列化往往比较吃性能,在高并发场景下会成为性能的瓶颈。protobuf的序列化和反序列化是一个可行的替代方案。
在使用之前,我们需要了解这两种方法的性能差异。在此基础上,顺便深入使用一benchmarking功能。
benchmarking
基准测试是衡量代码性能的重要技术,它能帮助你找出性能瓶颈,并优化函数以提升效率。
对于 Go 开发者而言,基准测试在以下场景中十分有用:比较不同实现方案的性能、针对特定用例优化代码,或者评估代码库变更带来的影响。
测试程序
package protoVsjson
import (
"encoding/json"
"testing"
"google.golang.org/protobuf/proto"
)
// JSON结构体定义(与Protobuf对应)
type ComplexMessageJSON struct {
ID int32 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Active bool `json:"active"`
Timestamp int64 `json:"timestamp"`
Score float32 `json:"score"`
Rating float64 `json:"rating"`
Data []byte `json:"data"`
Status int32 `json:"status"`
Address string `json:"address"`
Age int32 `json:"age"`
Phone string `json:"phone"`
Department string `json:"department"`
Salary float32 `json:"salary"`
Verified bool `json:"verified"`
LoginCount int32 `json:"login_count"`
LastLogin string `json:"last_login"`
Tags []string `json:"tags"`
Metadata map[string]string `json:"metadata"`
Priority int32 `json:"priority"`
}
// 创建测试数据
type testData struct {
protoMsg *ComplexMessage
jsonMsg *ComplexMessageJSON
}
func setupTestData() testData {
metadata := map[string]string{
"version": "1.0",
"source": "benchmark",
"env": "test",
}
tags := []string{"performance", "protobuf", "json", "benchmark"}
data := []byte{0x01, 0x02, 0x03, 0x04, 0x05}
return testData{
protoMsg: &ComplexMessage{
Id: 12345,
Name: "Performance Test User",
Email: "test@example.com",
Active: true,
Timestamp: 1620000000,
Score: 95.5,
Rating: 4.75,
Data: data,
Status: 2,
Address: "123 Test Street, Test City",
Age: 35,
Phone: "+1234567890",
Department: "Engineering",
Salary: 75000.50,
Verified: true,
LoginCount: 120,
LastLogin: "2023-01-15T10:30:00Z",
Tags: tags,
Metadata: metadata,
Priority: 1,
},
jsonMsg: &ComplexMessageJSON{
ID: 12345,
Name: "Performance Test User",
Email: "test@example.com",
Active: true,
Timestamp: 1620000000,
Score: