python 中序列化方式的比較

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
發佈了131 篇原創文章 · 獲贊 153 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章