Compress Python Object in Memory

前端 未结 3 1269
萌比男神i
萌比男神i 2021-01-31 21:36

Most tutorials on compressing a file in Python involve immediately writing that file to disk with no intervening compressed python object. I want to know how to pickle and then

3条回答
  •  梦如初夏
    2021-01-31 22:16

    I use this to save memory in one place:

    import cPickle
    import zlib
    
    # Compress:
    compressed = zlib.compress(cPickle.dumps(obj))
    
    # Get it back:
    obj = cPickle.loads(zlib.decompress(compressed))
    

    If obj has references to a number of small objects, this can reduce the amount of memory used by a lot. A lot of small objects in Python add up because of per-object memory overhead as well as memory fragmentation.

提交回复
热议问题