golang标准库json与三方包jsoniter序列化效率对比

golang标准库json与三方包jsoniter序列化效率对比

学习自:https://studygolang.com/articles/12702

测试代码

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结构体进行序列化,性能最佳

python2.7 vs python 3.7 vs pypy序列化

测试代码

#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秒
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值