点击蓝色字关注我们!

无论是在Web开发还是服务端开发,json格式都是相当常见的数据传输格式,一般情况下我们对于json的解析构造性能并不需要太多关心,除非是数据量很大或者性能要求较高的系统交互中。
在Python中json的序列化与反序列化有很多库,具体选择使用哪一个,或者哪一个速度更快呢?下面我们对5种常见的库进行对比:
-
ujson
-
yajl
-
cjson
-
simplejson
-
stdlib json
◆ ◆ ◆
测试方式:
json序列化与反序列化速度对比(按总时间排序:测试数据100 * 10000)ujson 序列化: 2.084 反序列化: 1.157 总时间: 3.241yajl 序列化: 1.910 反序列化: 1.970 总时间: 3.880cjson 序列化: 3.305 反序列化: 1.328 总时间: 4.632simplejson 序列化: 10.279 反序列化: 4.658 总时间: 14.937stdlib json 序列化: 7.013 反序列化: 8.594 总时间: 15.607
测试结论:
-
1.stdlib json也就是内置的json.dumps外,其他都是第三方包。
-
2.数据量较少时,速度几乎没有区别,无所谓选择哪一个。
-
3.数据量大的情况下,ujson的总体表现最好,但序列化不如yajl
在django中,如果只是response一个json对象,可以直接使用JsonResonse
用法为:
>>> from django.http import JsonResponse>>> response = JsonResponse({'foo': 'bar'})>>> response.content'{"foo": "bar"}'
默认采用内置stdlib方式进行json格式化后返回。如果数据不多,着实方便(django1.7引入)
◆ ◆ ◆
测试代码来自rtyler,在其基础上新增了ujson
import timeimport pickleimport yajltry: import cjsonexcept ImportError: cjson = Nonetry: import simplejsonexcept ImportError: simplejson = Nonetry: import ujsonexcept ImportError: ujson = Nonetry: import jsonexcept 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 -= 1 foo = f(data) return time.time() - startdef 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)) == 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))
◆ ◆ ◆
长按识别
关注 技术90分