Loading [MathJax]/extensions/MathZoom.js

基础知识

json和gob是go语言自带的序列化方式,都在encoding包下面。

go自带的json使用反射机制,效率低。easyjson在解析json数据的时候,并不是使用反射机制,而只针对预先定义好的json结构体对输入的json字符串进行纯字符串的截取,并将对应的json字段赋值给结构体。easyjson提供提供了代码生成工具easyjson -all <file>.go,可以一键生成go文件中定义的结构体对应的解析。

messagepack是一种十分高效的编码方式,在文件头加入“//go:generate msgp”,使用go generate xx.go命令生成文件。

protobuf有多个实现版本,官方版本使用了反射性能相对较差,对CPU和内存要求非常高的情况下可以使用FlatBuffers,一般推荐使用gogo-protobuf就足够用了。

要使用easyjson、msgp(全称message pack)和protobuf需要先安装:

go get github.com/mailru/easyjson

go get github.com/tinylib/msgp

go get github.com/gogo/protobuf/protoc-gen-gogofaster

安装后在$GOPATH/bin下生成easyjson、msgp、 protoc-gen-gogofaster三个可执行文件(如果用的是go1.7及以上版本,go get不会默认执行go install,执行go get后还需要手动执行go install,比如执行go install github.com/mailru/easyjson才会生成easyjson这个可执行文件)。

使用easyjson和msgp需要先写一个go文件,定义好要序列化的结构体。

person.go

//go:generate msgp<br>//easyjson不需要上面这一行
 
package serialize
 
type Person struct {
    DocId       uint32
    Position    string
    Company     string
    City        string
    SchoolLevel int32
    Vip         bool
    Chat        bool
    Active      int32
    WorkAge     int32
}

执行命令 easyjson -all ./serialize/person.go 会生成person_easyjson.go。

执行命令 go generate ./serialize/person.go 会生成person_gen.go和person_gen_test.go。Person结构体的序列化和反序列化函数就在person_gen.go文件里。

要使用protobuf需要先编写.proto文件,为保证对比的公平性,我们定义一个Doc,它跟Person的字段完全相同。

doc.proto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
syntax = "proto3";
package serialize;
 
message  Doc {
    uint32 doc_id = 1;
    string position = 2;
    string company = 3;
    string city = 4;
    int32 school_level = 5;
    bool vip = 6;
    bool chat = 7;
    int32 active = 8;
    int32 work_age=9;
}

 执行命令  protoc -I=. doc.proto --gogofaster_out=. 会生成doc.pb.go,Doc的序列化和反序列化函数就在这个文件里。

单元测试package serialize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package serialize
 
import (
    "bytes"
    "encoding/gob"
    "encoding/json"
    "fmt"
    "testing"
 
    "github.com/gogo/protobuf/proto"
    easyjson "github.com/mailru/easyjson"
    "github.com/tinylib/msgp/msgp"
)
 
var doc = Doc{DocId: 123, Position: "搜索工程师", Company: "百度", City: "北京", SchoolLevel: 2, Vip: false, Chat: true, Active: 1, WorkAge: 3}
var person = Person{DocId: 123, Position: "搜索工程师", Company: "百度", City: "北京", SchoolLevel: 2, Vip: false, Chat: true, Active: 1, WorkAge: 3}
 
func TestJson(t *testing.T) {
    bs, _ := json.Marshal(doc)
    fmt.Printf("json encode byte length %d\n", len(bs))
    var inst Doc
    _ = json.Unmarshal(bs, &inst)
    fmt.Printf("json decode position %s\n", inst.Position)
}
 
func TestEasyJson(t *testing.T) {
    bs, _ := person.MarshalJSON()
    fmt.Printf("easyjson encode byte length %d\n", len(bs))
    var inst Person
    _ = easyjson.Unmarshal(bs, &inst)
    fmt.Printf("easyjson decode position %s\n", inst.Position)
}
 
func TestGob(t *testing.T) {
    var buffer bytes.Buffer
    encoder := gob.NewEncoder(&buffer)
    _ = encoder.Encode(doc)
    fmt.Printf("gob encode byte length %d\n", len(buffer.Bytes()))
    var inst Doc
    decoder := gob.NewDecoder(&buffer)
    _ = decoder.Decode(&inst)
    fmt.Printf("gob decode position %s\n", inst.Position)
}
 
func TestGogoProtobuf(t *testing.T) {
    bs, _ := proto.Marshal(&doc)
    fmt.Printf("pb encode byte length %d\n", len(bs))
    var inst Doc
    _ = proto.Unmarshal(bs, &inst)
    fmt.Printf("pb decode position %s\n", inst.Position)
}
 
func TestMsgp(t *testing.T) {
    var buf bytes.Buffer
    _ = msgp.Encode(&buf, &person)
    fmt.Printf("msgp encode byte length %d\n", len(buf.Bytes()))
    var inst Person
    _ = msgp.Decode(&buf, &inst)
    fmt.Printf("msgp decode position %s\n", inst.Position)
}

  

基准测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
func BenchmarkJsonEncode(b *testing.B) {
    for i := 0; i < b.N; i++ {
        json.Marshal(doc)
    }
}
 
func BenchmarkJsonDecode(b *testing.B) {
    bs, _ := json.Marshal(doc)
    var inst Doc
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        json.Unmarshal(bs, &inst)
    }
}
 
func BenchmarkEasyJsonEncode(b *testing.B) {
    for i := 0; i < b.N; i++ {
        person.MarshalJSON()
    }
}
 
func BenchmarkEasyJsonDecode(b *testing.B) {
    bs, _ := person.MarshalJSON()
    var inst Person
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        easyjson.Unmarshal(bs, &inst)
    }
}
 
func BenchmarkGobEncode(b *testing.B) {
    for i := 0; i < b.N; i++ {
        var buffer bytes.Buffer
        encoder := gob.NewEncoder(&buffer)
        encoder.Encode(doc)
    }
}
 
func BenchmarkGobDecode(b *testing.B) {
    var buffer bytes.Buffer
    encoder := gob.NewEncoder(&buffer)
    encoder.Encode(doc)
    var inst Doc
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        buffer.Reset()
        decoder := gob.NewDecoder(&buffer)
        decoder.Decode(&inst)
    }
}
 
func BenchmarkPbEncode(b *testing.B) {
    for i := 0; i < b.N; i++ {
        proto.Marshal(&doc)
    }
}
 
func BenchmarkPbDecode(b *testing.B) {
    bs, _ := proto.Marshal(&doc)
    var inst Doc
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        proto.Unmarshal(bs, &inst)
    }
}
 
func BenchmarkMsgpEncode(b *testing.B) {
    for i := 0; i < b.N; i++ {
        var buf bytes.Buffer
        msgp.Encode(&buf, &person)
    }
}
 
func BenchmarkMsgpDecode(b *testing.B) {
    var buf bytes.Buffer
    msgp.Encode(&buf, &person)
    var inst Person
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        buf.Reset()
        msgp.Decode(&buf, &inst)
    }
}

在跑基础测试时我们通过-benchmem 把内存的使用情况也输出。

    速度 ns/op 内存开销 B/op
序列化 json 982 224
easyjson 643 720
gob 5714 1808
gogo-protobuf 114 48
msgpack 311 160
反序列化 json 2999 256
easyjson 951 32
gob 338 288
gogo-protobuf 173 32
msgpack 131 32

 

 结论:

第一梯队:gogo-protobuf序列化比msgp快2倍多,反序列化相差不多。

第二梯队:easyjson比json的主要优势体现在反序列化方面,快了3倍,序列化快的不多。gob的反序列化比json快了9倍,但序列化却比json慢了5倍多。

posted on   高性能golang  阅读(5321)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示