python中5个json库的速度对比,你猜对了吗
生活随笔
收集整理的这篇文章主要介绍了
python中5个json库的速度对比,你猜对了吗
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
python中json的序列化与反序列化有很多库,具体选择使用哪一个,或者哪一个速度更快呢?
先上结果
json序列化与反序列化速度对比(按总时间排序:测试数据100 * 10000)
| 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引入)
测试代码
import time import pickle import yajltry:import cjson except ImportError:cjson = None try:import simplejson except ImportError:simplejson = None try:import ujson except ImportError:ujson = Nonetry:import json except ImportError:json = Nonedefault_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 -= 1foo = f(data)return time.time() - startdef profile(serial, deserial, data=None, x=100 * 10000):if not data:data = default_datasquashed = serial(data)return (ttt(serial, data, x), ttt(deserial, squashed, x))def test(serial, deserial, data=None):if not data:data = default_dataassert deserial(serial(data)) == data ''' 学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:725638078 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! '''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))总结
以上是生活随笔为你收集整理的python中5个json库的速度对比,你猜对了吗的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: python基础入门:实现(无重复字符)
- 下一篇: Python 多进程异常处理的方法,你会