python中5个json库的速度对比
python中json的序列化与反序列化有很多库,具体选择使用哪一个,或者哪一个速度更快呢?
先上结果
json序列化与反序列化速度对比(按总时间排序:测试数据100 * 10000) ujson 序列化: 2.084 反序列化: 1.157 总时间: 3.241 yajl 序列化: 1.910 反序列化: 1.970 总时间: 3.880 cjson 序列化: 3.305 反序列化: 1.328 总时间: 4.632 simplejson 序列化: 10.279 反序列化: 4.658 总时间: 14.937 stdlib json 序列化: 7.013 反序列化: 8.594 总时间: 15.607
其中,除了stdlib json也就是内置的json.dumps外,其他都是第三方包。数据量较少时,速度几乎没有区别,无所谓选择哪一个。数据量大的情况下,ujson的总体表现最好,但序列化不如yajl
而django中,如果只是response一个json对象,可以直接使用JsonResonse
用法为:
>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
'{"foo": "bar"}'默认采用内置方式进json格式化后返回。如果数据不多,着实方便(django1.7引入)
测试代码
来自rtyler,在其基础上新增了ujson
import time
import pickle
import yajl
try:
import cjson
except ImportError:
cjson = None
try:
import simplejson
except ImportError:
simplejson = None
try:
import ujson
except ImportError:
ujson = None
try:
import json
except ImportError:
json = None
default_data = {
"name": "Foo",
"type": "Bar",
"count": 1,
"info": {
"x": 203,
"y": 102, }, }
def ttt(f, data=None, x=100 * 10000):
start = time.time()
while x:
x -= 1
foo = f(data)
return time.time() - start
def profile(serial, deserial, data=None, x=100 * 10000):
if not data:
data = default_data
squashed = serial(data)
return (ttt(serial, data, x), ttt(deserial, squashed, x))
def test(serial, deserial, data=None):
if not data:
data = default_data
assert deserial(serial(data)) == data
contenders = [
('yajl', (yajl.Encoder().encode, yajl.Decoder().decode)),
]
if cjson:
contenders.append(('cjson', (cjson.encode, cjson.decode)))
if simplejson:
contenders.append(('simplejson', (simplejson.dumps, simplejson.loads)))
if json:
contenders.append(('stdlib json', (json.dumps, json.loads)))
if ujson:
contenders.append(('ujson', (ujson.dumps, ujson.loads)))
for name, args in contenders:
test(*args)
x, y = profile(*args)
print("%-11s serialize: %0.3f deserialize: %0.3f total: %0.3f" % (
name, x, y, x + y)) 相关推荐
Lzs 2020-10-23
xclxcl 2020-08-03
zmzmmf 2020-08-03
葫芦小金刚 2020-07-22
ericdoug 2020-07-18
Erick 2020-06-17
aanndd 2020-06-16
Erick 2020-06-17
aanndd 2020-06-16
xuebingnan 2020-06-13
80337960 2020-06-10
Jerry 2020-06-01
mengdg000 2020-05-29
spring-data-redis RedisTemplate 操作redis时发现存储在redis中的key不是设置的string值,前面还多出了许多类似\xac\xed\x00\x05t\x00;
尹小鱼 2020-05-29
somebodyoneday 2020-05-15
visionzheng 2020-05-05
visionzheng 2020-05-04
igogo00 2020-05-03