除了cPickle,cjson外还有没有更高效点的序列化库了
除了cPickle,cjson外还有没有更高效点的序列化库了
http://blog.csdn.net/chen_lovelotus/article/details/7228745
msgpack最快,而且是跨语言的,二进制,但只能打包简单的list,dict,int,string,unicode,在memcache之类的
字符串协议里会有问题。
marshal其次,也是二进制的,可以打包大多数python对象,缺点同msgpack,另文档上说各版本的python实现会不一样,但我这测下
来三台机器分别是stackless 2.6.5 2.7.2 python 2.6.2之间都没出现兼容问题
tnetstring速度第三,字符打包,可以完美支持各种协议的后端,但有一个致命的缺点就是支持类型太少,比如下面的代码mongo里出来的
unicode就无法打包。
以上三者速度差距很小很小。
bson,cPickle,json都很慢。。直接pass
cPickle_test used time 1.32382702827s
marshal_test used time 0.29944396019s
msgpackb_test used time 0.23744893074s
#!/usr/bin/env Python
#coding=utf-8
'''
Created on Jul 13, 2011
@author: apple
'''
import time,functools
import cPickle,marshal,tnetstring,bson,msgpack
import pymongo
data = pymongo.Connection().freeasker.question.find_one()
data.pop('_id')
def timeit(func):
@functools.wraps(func)
def __do__(*args,**wk):
start = time.time()
result= func(*args,**wk)
print '%s used time %ss'%(func.__name__,time.time()-start)
return result
return __do__
@timeit
def cPickle_test(c,data):
for i in xrange(c):
s = cPickle.dumps(data)
cPickle.loads(s)
@timeit
def marshal_test(c,data):
for i in xrange(c):
s = marshal.dumps(data)
marshal.loads(s)
@timeit
def tnetstring_test(c,data):
for i in xrange(c):
s = tnetstring.dumps(data)
tnetstring.loads(s)
@timeit
def bson_test(c,data):
for i in xrange(c):
s = bson.dumps(data)
bson.loads(s)
@timeit
def msgpackb_test(c,data):
# packer = msgpack.Packer()
for i in xrange(c):
s = msgpack.packb(data)
msgpack.unpackb(s)
@timeit
def msgpack_test(c,data):
packer = msgpack.Packer()
for i in xrange(c):
s = packer.pack(data)
packer.unpack(s)
if __name__ == '__main__':
count = 10000
data = pymongo.Connection().freeasker.question.find_one()
data.pop('_id')
cPickle_test(count, data)
marshal_test(count, data)
# tnetstring_test(count, data)
# bson_test(count, data)
# msgpack_test(count, data)
msgpackb_test(count, data)