简体   繁体   English

Python:StringIO之间共享内存?

[英]python: memory shared between StringIO?

Is the memory shared between the StringIO if I do that? 如果这样做,是否在StringIO之间共享内存? I have the feeling it is because the memory of the python process did not increase on line 6. 我的感觉是因为python进程的内存没有在第6行增加。

In [1]: from StringIO import StringIO
In [2]: s = StringIO()
In [3]: s.write('abcd'*10000000) # memory increases
In [4]: s.tell()
Out[4]: 40000000
In [5]: s.seek(0)
In [6]: a = StringIO(s.read()) # memory DOES NOT increase
In [7]: a.tell()
Out[7]: 0
In [8]: a.read(10)
Out[8]: 'abcdabcdab'

However my concern is that when I delete those 2 variables, the memory consumption of the python process does not decrease anymore... why ? 但是我担心的是,当我删除这两个变量时,python进程的内存消耗不再减少了……为什么? Does this code create a memory leak ? 此代码是否会造成内存泄漏?

When I just used one variable, the memory is well freed when I delete the variable. 当我只使用一个变量时,删除该变量后内存释放良好。

I'd be curious to better understand what is going on here. 我很好奇这是怎么回事。 Thanks. 谢谢。

A StringIO() object does not make a copy of a string passed to it. 一个StringIO()对象不会使传递给它一个字符串的副本。 There is no need to, as strings are not mutable. 不需要,因为字符串不是可变的。

When reading data from a StringIO() object in chunks, new string objects are created that are substrings from the original input string. StringIO()对象StringIO()块读取数据时,将创建新的字符串对象,这些对象是原始输入字符串的子字符串。

Memory consumption never goes down immediately when freeing objects. 释放对象时,内存消耗永远不会立即下降。 Memory allocation is only redistributed as needed by the OS, and many types of (small) objects can be interned by Python for efficiency and are never freed, only reused. 内存分配仅根据OS的需要重新分配,许多类型的(小)对象可以由Python插入以提高效率,并且永远不会释放,只能重用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM