package main
import (
"encoding/json"
"fmt"
"github.com/json-iterator/go"
"time"
)
type Data struct {
ceshi string
ceshi1 string
ceshi2 string
ceshi3 string
}
func main() {
data := Data{
ceshi: "ceshi111111111111111111111111111111111111111",
ceshi1: "ceshi111111111111111111111111111111111111111",
ceshi2: "ceshi111111111111111111111111111111111111111",
ceshi3: "ceshi111111111111111111111111111111111111111",
}
t1 := time.Now()
for i := 0; i < 100000; i++ {
json.Marshal(&data)
}
cost := time.Since(t1).Seconds()
fmt.Printf("encoding/json, using struct %v 秒\n", cost)
var jsoner = jsoniter.ConfigCompatibleWithStandardLibrary
t2 := time.Now()
for i := 0; i < 100000; i++ {
jsoner.Marshal(&data)
}
cost = time.Since(t2).Seconds()
fmt.Printf("json-iterator, using struct %v 秒\n", cost)
data1 := map[string]string{}
data1["ceshi"] = "ceshi11111111111111111111111"
data1["ceshi1"] = "ceshi11111111111111111111111"
data1["ceshi2"] = "ceshi11111111111111111111111"
data1["ceshi3"] = "ceshi11111111111111111111111"
t3 := time.Now()
for i := 0; i < 100000; i++ {
json.Marshal(&data1)
}
cost = time.Since(t3).Seconds()
fmt.Printf("encoding/json,using map %v秒\n", cost)
t4 := time.Now()
for i := 0; i < 100000; i++ {
jsoner.Marshal(&data1)
}
cost = time.Since(t4).Seconds()
fmt.Printf("json-iterator, using map %v秒\n", cost)
}
encoding/json, using struct 0.01814627 秒
json-iterator, using struct 0.017017023 秒
encoding/json,using map 0.270127329秒
json-iterator, using map 0.223476829秒
使用json-iterator
库+struct
结构体进行序列化,性能最佳
测试代码
#encoding:utf-8
import json
import time
data = {}
data["ceshi"] = "ceshi11111111111111111111111"
data["ceshi1"] = "ceshi11111111111111111111111"
data["ceshi2"] = "ceshi11111111111111111111111"
data["ceshi3"] = "ceshi11111111111111111111111"
t1 = time.time()
#python 2.7 用xrange
for i in range(100000):
j = json.dumps(data)
cost = time.time() - t1
print("python 3.7 序列化耗时 %s"%cost)
python 2.7 序列化耗时 0.56022310257秒
python 3.7 序列化耗时 0.57580351829秒
pypy 3.6 序列化耗时 0.1422567367553711秒