python 中序列化方式的比较

本文对比了Python中两种常见的序列化方式:pickle和json。json在性能上更优,速度快且生成的字符串体积小,适用于跨语言数据交换;而pickle能序列化复杂的Python类型,包括函数和类,更适合于Python内部的数据交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python 中序列化方式的比较(pickle, json)

相同点, 都能够用来序列化数据,返回字符串。
下面主要是来说明一下区别

性能

通过简单测试看到序列化相同数据,json速度显然要快一些,大约是20~30倍,同时得到的字符串的体积上也有不同
json 相对较小,数据结构不同,差别也有不同。

总结来说,json 性能较好(对于另外的类型还需验证) 如果必要使用pickle ,可以使用更快的cPickle

适用性

json 适合跨语言的数据交换,pickle 是适用于python的数据的序列化.

区别就是json适用的数据只是一些基本类型,pickle 可以将python 里面的类型都给序列化(包括函数,类,实例)。

所以就是 在使用的时候,涉及到跨语言或是简单类型的数据交换 使用json。 对于python 语言之间,类型复杂的数据交换则用pickle

下面是测试的代码 和 pickle 序列化数据的时候的关键内容:

下面主要是序列化了10万 列表类型的数据和 字典类型的数据

# coding=utf8
# Time    : 2020/1/15 14:17
# File    : json_pickle.py
# Software: PyCharm
import json
import pickle
import time
from contextlib import wraps


def tt(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        _s = time.time()
        value = func(*args, **kwargs)
        _e = time.time()
        print _e - _s, len(value)
        return value

    return wrapper


@tt
def test_json(objs):
    ts = json.dumps(objs)
    return ts


@tt
def test_pickle(objs):
    ts = pickle.dumps(objs)
    return ts


def test(x):
    test_json(x)
    test_pickle(x)
    print "--" * 30


if __name__ == '__main__':
    l = 100000
    x = [i for i in range(l)]
    print "list:"
    test(x)

    d = dict([(str(i), i) for i in range(l)])
    print "dict:"
    test(d)

下面是代码来自pickle源码:

# pickle.py

class Pickler:
    def save_dict(self, obj):
        write = self.write

        if self.bin:
            write(EMPTY_DICT)
        else:   # proto 0 -- can't use EMPTY_DICT
            write(MARK + DICT)

        self.memoize(obj)
        self._batch_setitems(obj.iteritems())

    dispatch[DictionaryType] = save_dict
    if not PyStringMap is None:
        dispatch[PyStringMap] = save_dict

    def _batch_setitems(self, items):
        # Helper to batch up SETITEMS sequences; proto >= 1 only
        pass

    def save_inst(self, obj):
        pass

    dispatch[InstanceType] = save_inst

    def save_global(self, obj, name=None, pack=struct.pack):
        """代码省略可以去源码查看"""
        pass

    dispatch[ClassType] = save_global
    dispatch[FunctionType] = save_global
    dispatch[BuiltinFunctionType] = save_global
    dispatch[TypeType] = save_global
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值