Python 数据结构内存占用是原始数据的 5 倍左右
大概是如下结构体
[{dic1….},{key1:[value1,value2…],key2:[value1,value2…]},{dic3},{dic4}]
1.5g 数据要 7g 多内存,请问这是正常的内存占用么,要是优化的话在哪方面优化呢,请教各位~
大概是如下结构体
[{dic1….},{key1:[value1,value2…],key2:[value1,value2…]},{dic3},{dic4}]
1.5g 数据要 7g 多内存,请问这是正常的内存占用么,要是优化的话在哪方面优化呢,请教各位~
A Python array is as lean as a C array. When creating an array, you provide a typecode, a letter to determine the underlying C type used to store each item in the array. For example, b is the typecode for signed char. If you create an array(‘b’), then each item will be stored in a single byte and interpreted as an integer from –128 to 127. For large sequences of numbers, this saves a lot of memory. And Python will not let you put any number that does not match the type for the array.
如果是 homogeneous data structure,可以用上说的 numpy,pandas,array 等库。
另外可以考虑转换成数据库数据,需要访问数据时再和数据库进行交互,就不必把所有数据都一下子挤进内存中。顺带一提 Python 有原生自带数据库交互库叫做 sqlite3.
看你列出的数据的格式,似乎像是 JSON,可以用一些 lazy-parse json 的库,例如 ijson ( https://pypi.org/project/ijson/), json-streamer ( https://github.com/kashifrazzaqui/json-streamer), bigjson ( https://github.com/henu/bigjson), jsonslicer ( https://pypi.org/project/jsonslicer/).
如果对精度要求不高,可以用一些 succinct data structure 来大大简化数据结构空间开销,例如布隆过滤器,HyperLogLog,Count-Min sketch 等。
关于数据空间占用的优化,可以看经典的《 Python 高性能编程》,里面除了讲 Python 代码如何提升时间性能,还讲了 Python 代码如何提升空间性能,讲的非常全面细致,大部分可用的选项都覆盖了.