1. 程式人生 > >go隨聊-號稱全宇宙最快的json解析包

go隨聊-號稱全宇宙最快的json解析包

A high-performance 100% compatible drop-in replacement of "encoding/json"

吐槽一下,這麼NB了一個logo都沒有:)

How to get

go get github.com/json-iterator/go

Usage

100% compatibility with standard lib

Replace

import "encoding/json"
json.Marshal(&data)

with

import "github.com/json-iterator/go"

var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Marshal(&data)

Replace

import "encoding/json"
json.Unmarshal(input, &data)

with

import "github.com/json-iterator/go"

var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Unmarshal(input, &data)

解碼比對

import (
	"fmt"
	"testing"
	"encoding/json"
	"github.com/Jeffail/gabs"
	"github.com/json-iterator/go"
)

type Data struct {
	Id string 				`json:"id"`
	ValueInt int64 			`json:"valueInt"`
	ValueFloat float64 		`json:"valueFloat"`
	ValueString string 		`json:"valueString"`
}
func TestDecode(t *testing.T) {
	jsonData:=gabs.New()
	jsonData.Set("1234567890","id")
	jsonData.Set(123,"valueInt")
	jsonData.Set(123.456,"valueFloat")
	jsonData.Set("aaaaaaaaaaaaaaaaaab","valueString")
	bytes:=jsonData.Bytes()

	//標準庫解碼1000000次
	{
		data:=&Data{}
		start:=CurrentTime()
		for i:=0;i<1000000;i++ {
			err:=json.Unmarshal(bytes,data)
			if err!=nil {
				fmt.Println(err)
			}
		}
		end:=CurrentTime()
		//列印總耗時
		fmt.Println("use time:",end-start)
		fmt.Println(data)
	}

	//NB庫解碼1000000次
	{
		var json = jsoniter.ConfigCompatibleWithStandardLibrary
		data:=&Data{}
		start:=CurrentTime()
		for i:=0;i<1000000;i++ {
			err:=json.Unmarshal(bytes,data)
			if err!=nil {
				fmt.Println(err)
			}
		}
		end:=CurrentTime()
		//列印總耗時
		fmt.Println("fast use time:",end-start)
		fmt.Println(data)
	}
}
-----------------------------------------------------
use time: 2714
&{1234567890 123 123.456 aaaaaaaaaaaaaaaaaab}
fast use time: 737
&{1234567890 123 123.456 aaaaaaaaaaaaaaaaaab}

結果來看標準庫用時2714毫秒,nb庫用時737毫秒,確實比標準庫快很多。

編碼比對

import (
	"fmt"
	"testing"
	"encoding/json"
	"github.com/json-iterator/go"
)

type Data struct {
	Id string 				`json:"id"`
	ValueInt int64 			`json:"valueInt"`
	ValueFloat float64 		`json:"valueFloat"`
	ValueString string 		`json:"valueString"`
}
func TestEncode(t *testing.T) {
	data:=&Data{
		Id:"1234",
		ValueInt:123,
		ValueFloat:123.456,
		ValueString:"12345",
	}
	//標準庫編碼1000000次
	{
		start:=CurrentTime()
		for i:=0;i<1000000;i++ {
			_,err:=json.Marshal(data)
			if err!=nil {
				fmt.Println(err)
			}
		}
		end:=CurrentTime()
		//列印總耗時
		fmt.Println("use time:",end-start)
	}

	//NB庫編碼1000000次
	{
		var json = jsoniter.ConfigCompatibleWithStandardLibrary
		start:=CurrentTime()
		for i:=0;i<1000000;i++ {
			_,err:=json.Marshal(data)
			if err!=nil {
				fmt.Println(err)
			}
		}
		end:=CurrentTime()
		//列印總耗時
		fmt.Println("fast use time:",end-start)
	}
}
-------------------------------------------------------
use time: 1058
fast use time: 727

結果來看標準庫用時1058毫秒,nb庫用時727毫秒,確實比標準庫快很多。