go語言序列化json/gob/msgp/protobuf性能對比


基礎知識

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
//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

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

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)
}

  

基准測試

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倍多。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM