python - 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()
方法。但我想知道对象在内存中的表示方式。
解决方案
如果你想看看它是如何工作的,你可以阅读io.StringIO
CPython 代码库中的源代码: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())
推荐阅读
- excel - 查找两个 dd/mm/yyyy hh:mm 之间的时差
- python - 为列表中的每个元素调用 API
- r - 将df列表中的df随机划分为相等的子集
- amazon-web-services - 基于令牌的 docker 访问
- ejs - 在 ejs 'Scriptlet' 标记内呈现不同的数据值
- ios - AVFoundation - 视频合并但只播放最后一个视频
- javascript - 如何修复 Google OAuth 401 错误无效客户端?
- angular - 如何在离子角度项目中使用 SVG 精灵?
- templates - 使用文档作为模板:标题编号问题
- c++ - 只有一名成员的匿名工会