python中5个json库的速度对比

python中5个json库的速度对比python中json的序列化与反序列化有很多库,具体选择使用哪一个,或者哪一个速度更快呢?先上结果json序列化与反序列化速度对比(按总时间排

大家好,欢迎来到IT知识分享网。

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

python中5个json库的速度对比

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

欢迎大家关注我的头条号,私信“python”,学习资料包免费分享给需要的朋友,另有python学习交流群,可以交流学习拓展人脉。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/56430.html

(0)
上一篇 2024-07-22 10:00
下一篇 2024-07-22 16:33

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信