StringIO在哪里分配内存

Where does StringIO allocates memory

可能是个愚蠢的问题: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() 方法。但是我想知道对象在内存中是如何表示的。

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

我找到了我的问题的答案,即“Does StringIO(initial_value) copy the underlying string to the buffer (if you only read it)”,是的(看_io_StringIO___init___impl(), 来自第 732 行 (https://github.com/python/cpython/blob/main/Modules/_io/stringio.c#L732), and then at write_str() https://github.com/python/cpython/blob/main/Modules/_io/stringio.c#L177)

回到你的问题,有一个 C-struct stringio,它的值为 buf_size -- 这是 StringIO 中实际分配的字节数,可能更大比你输入的字节数还多!

实际上,StringIO overallocates 以防万一,大约 1.125 次,预见未来会增加缓冲区,https://github.com/python/cpython/blob/main/Modules/_io/stringio.c#L99

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

len(buff.getvalue())