python中5个json库的速度对比
生活随笔
收集整理的這篇文章主要介紹了
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
用法為:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' >>> from django.http import JsonResponse >>> response = JsonResponse({'foo': 'bar'}) >>> response.content '{"foo": "bar"}'默認采用內置方式進json格式化后返回。如果數據不多,著實方便(django1.7引入)
測試代碼
來自rtyler,在其基礎上新增了ujson
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import timeimport 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)) == datacontenders = [('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库的速度对比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python2/3 中删除字典中valu
- 下一篇: Python 中,字符串连接效率最高的方