【发布时间】:2022-01-03 11:10:41
【问题描述】:
我需要将整数存储为字符串。例如。 - [1,2,3] 将存储为 '1;2;3'。为此,我需要首先将整数列表转换为字符串列表。但是这种转换的内存使用量很大。
显示问题的示例代码。
from sys import getsizeof
import tracemalloc
tracemalloc.start()
curr, peak = tracemalloc.get_traced_memory()
print((f'Current: {round(curr/1e6)} MB\nPeak: {round(peak/1e6)} MB'))
print()
list_int = [1]*int(1e6)
curr, peak = tracemalloc.get_traced_memory()
print((f'Current: {round(curr/1e6)} MB\nPeak: {round(peak/1e6)} MB'))
print(f'Size of list_int: {getsizeof(list_int)/1e6} MB')
print()
list_str = [str(i) for i in list_int]
curr, peak = tracemalloc.get_traced_memory()
print((f'Current: {round(curr/1e6)} MB\nPeak: {round(peak/1e6)} MB'))
print(f'Size of list_str: {getsizeof(list_str)/1e6} MB')
输出:
Current: 0 MB
Peak: 0 MB
Current: 8 MB
Peak: 8 MB
Size of list_int: 8.000056 MB
Current: 66 MB
Peak: 66 MB
Size of list_str: 8.448728 MB
两个列表占用的内存差不多(8 MB),但程序在转换过程中使用的内存很大(66 MB)。
如何解决这个内存问题?
编辑:我需要将它转换为字符串,所以最后我会运行';'.join(list_str)。所以,即使我使用生成器/迭代器,比如说list_str = map(str, list_int),内存使用情况也是一样的。
【问题讨论】:
-
我不知道为什么会这样,但是使用可迭代对象怎么样?例如,
list_str = map(str, list_int)。这不会存储整个字符串列表,因此您可以使用更少的内存。 -
@j1-lee 是的,但是正如我提到的,我的最终目标是创建一个字符串,所以当我运行';'.join(list_str) 时,使用你提到的可迭代,内存使用量变得相同.
-
啊,你是对的。
-
@aniketsharma00411 与列表理解相比,生成器内存使用量将太少。请参阅下面的答案。
-
@TimRoberts 66MB 并不大,但是当我在我的应用程序中运行类似的东西时,大小为 60 MB 的 list_str 的内存消耗为 560+ MB,这会使我的服务器崩溃。我展示的代码只是一个例子。
标签: python python-3.x string list