go的序列化和反序列化的原生和插件比较多,这里使用一个 json-iterator
示例如下:
package main
import (
//"encoding/json"
"fmt"
"github.com/json-iterator/go"
)
func main() {
jjson()
}
func jjson() {
var jsonBlob = []byte(`[
{"Name": "张三", "Order": "Monotremata"},
{"Name": "李四", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
var json_iterator = jsoniter.ConfigCompatibleWithStandardLibrary
json_iterator.Unmarshal(jsonBlob, &animals)
fmt.Printf("animals...Unmarshal....%+v", animals)
b := Json(animals)
fmt.Printf("b....Marshal...", string(b))
}
func Json(i interface{}) []byte {
var json_iterator = jsoniter.ConfigCompatibleWithStandardLibrary
outi, err := json_iterator.Marshal(i)
if err != nil {
fmt.Println("WriteFile...JsonMarshal...error.....:", err)
}
return outi
}
相关地址:
https://github.com/json-iterator/go
官方benchmark 测试如下:
自测对比顺序
序列化
json.Marshal(data)
jsoniter.Marshal(data)
反序列化
json.Unmarshal([]byte(str), &Msg)
jsoniter.Unmarshal([]byte(str), &Msg)
1、1000个时间消耗
序列化
time cost = 4.0002ms
time cost = 3.0002ms
反序列化
time cost = 15.0008ms
time cost = 4.0003m
2、10000个时间消耗
序列化
time cost = 36.0021ms
time cost = 22.0013ms
反序列化
time cost = 145.0083ms
time cost = 39.0022ms
3、100000个时间消耗
序列化
time cost = 351.02ms
time cost = 237.0136ms
反序列化
time cost = 1.4610835s
time cost = 392.0225ms
1、1000000个时间消耗
序列化
time cost = 3.4391967s
time cost = 2.3011316s
反序列化
time cost = 14.4888287s
time cost = 3.863221s
|
请发表评论