首页 > 解决方案 > StringIO在哪里分配内存

问题描述

可能是愚蠢的问题:StringIO 在哪里分配内存?

from cStringIO import StringIO
import sys


buff = StringIO()
buff.write('This goes into the buffer. Don"t know what to say more.')
print(buff.__sizeof__())
buff.write('This goes next. blablablabla!!1!!!!')
print(sys.getsizeof(buff))

>> 56
>> 56

我知道.tell()方法。但我想知道对象在内存中的表示方式。

标签: pythonpython-2.7memoryiosize

解决方案


如果你想看看它是如何工作的,你可以阅读io.StringIOCPython 代码库中的源代码:https ://github.com/python/cpython/blob/main/Modules/_io/stringio.c

我找到了我的问题的答案,即“StringIO(initial_value) 是否将底层字符串复制到缓冲区(如果您只读取它)”,这是肯定的(看_io_StringIO___init___impl(),从第 732 行开始(https://github.com /python/cpython/blob/main/Modules/_io/stringio.c#L732),然后在write_str() https://github.com/python/cpython/blob/main/Modules/_io/stringio.c#L177

回到您的问题,有 C-struct stringio,它具有值buf_size- 这是 StringIO 中分配的实际字节数,可能大于您放入的字节数!

实际上,StringIO 过度分配以防万一,大约 1.125 倍,预见到缓冲区的未来添加,https://github.com/python/cpython/blob/main/Modules/_io/stringio.c#L99

不幸的是,我们无法buf_size从 Python 访问 struct 成员。如果你想跟踪你写了多少,要么总结来自 的回报.write(),相信.tell()告诉你的,或者取出字符串并检查它的长度:

len(buff.getvalue())

推荐阅读