高性能json序列化sonic

字节公司研究的,与标准库json用法相同

package test01

import (
	"encoding/json"
	"fmt"
	"github.com/bytedance/sonic"
	"testing"
)

type Book struct {
	Name   string `json:"title"`
	Price  float64
	Tags   []string
	Press  string
	Author People
}

type People struct {
	Name    string
	Age     int
	School  string
	Company string
	Title   string
}

var (
	people = People{
		Name:    "张三",
		Age:     18,
		School:  "大学",
		Company: "xx公司",
		Title:   "开发工程师",
	}
	book = Book{
		Name:   "高性能golang",
		Price:  58.0,
		Tags:   []string{"golang", "编程", "计算机"},
		Press:  "机械工业出版社",
		Author: people,
	}
)

func TestStdJson(t *testing.T) {
	// 用标准库进行json序列化。输出是[]byte
	if bs, err := json.Marshal(book); err != nil {
		fmt.Println(err)
		t.Fail()
	} else {
		fmt.Println(string(bs))

		// 用标准库进行json反序列化。输入是[]byte
		var book2 Book
		if err := json.Unmarshal(bs, &book2); err != nil {
			fmt.Println(err)
			t.Fail()
		} else {
			fmt.Printf("%+v\n", book2)
		}
	}
}
func TestSonic(t *testing.T) {
	// 用Sonic库进行json序列化。输出是[]byte
	if bs, err := sonic.Marshal(book); err != nil {
		fmt.Println(err)
		t.Fail()
	} else {
		fmt.Println(string(bs))

		// 用Sonic库进行json反序列化。输入是[]byte
		var book2 Book
		if err := sonic.Unmarshal(bs, &book2); err != nil {
			fmt.Println(err)
			t.Fail()
		} else {
			fmt.Printf("%+v\n", book2)
		}
	}
}
func BenchmarkStdJson(b *testing.B) {
	for i := 0; i < b.N; i++ {
		bs, _ := json.Marshal(book)
		var book2 Book
		json.Unmarshal(bs, &book2)
	}
}

func BenchmarkSonic(b *testing.B) {
	for i := 0; i < b.N; i++ {
		bs, _ := sonic.Marshal(book)
		var book2 Book
		sonic.Unmarshal(bs, &book2)
	}
}

cmd运行

go test -v ./service -run=TestStdJson -count=1
go test -v ./service -run=TestSonic -count=1

go test ./service -bench=BenchmarkStdJson -run=none -count=1 -benchmem -benchtime=2s
go test ./service -bench=BenchmarkSonic -run=none -count=1 -benchmem -benchtime=2s 

性能结果

标准库json

PS E:\go_work\mytest\test01> go test -bench=BenchmarkStdJson -run=none -count=1 -benchmem -benchtime=2s                                                 
goos: windows
goarch: amd64
pkg: go_work/mytest/test01
cpu: AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx
BenchmarkStdJson-8        212041             11116 ns/op             984 B/op         22 allocs/op                                 //平均每次耗时11116纳秒   //每次需要984B内存
//每次需要22次内存申请
PASS
ok      go_work/mytest/test01   3.101s

sonic

PS E:\go_work\mytest\test01> go test -bench=BenchmarkSonic -run=none -count=1 -benchmem -benchtime=2s 
goos: windows
goarch: amd64
pkg: go_work/mytest/test01
cpu: AMD Ryzen 5 3550H with Radeon Vega Mobile Gfx
BenchmarkSonic-8          702612              3143 ns/op            1099 B/op         10 allocs/op
PASS
ok      go_work/mytest/test01   2.863s



posted @ 2023-07-17 23:35  Bre-eZe  阅读(285)  评论(1)    收藏  举报