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))


作者:二二向箔
链接:https://www.jianshu.com/p/c90f5b471e99
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自www.cnblogs.com/ExMan/p/11269041.html