当前位置

cPickle 和 marshal 到底哪个快?

为了将 python 对象得以持久化保持(比如为了 web app 的 session/cache 需要),我们不得不将其序列化后转成字符串扔进文件或者数据库里。

Python 提供了两个基于 C 的模块 cPickle 和 marshal 来做这个序列化反序列化的操作。marshal 貌似仅限于少数几种 python 内置数据对象,所以想象起来好像 marshal 比 cPickle 要快一些,而且我们自己做的几次benchmark好像也证明了这点。但实际上果真如此吗?

scaner 也曾写 blog 说明他的测试是 marshal 比 cPickle 快,但有留言说用同样的程序得到了相反的结论..

今天在搜索中发现有老外做过比较全面的测试(07年10月18日的文章),结论是在某些情况下--比如浮点数、长的字符串--cPickle 是比 marshal 要快滴。最后他的建议是: "...even for simple data structures, for a caching layer you might as well use cPickle; you are not particularly slower for the thing you're going to be doing a lot, and you get a bunch of (potential) benefits in return."

其测试程序在http://utcc.utoronto.ca/~cks/programs/python/marshal-vs-cpickle.py

Topic: