garbage collection in python
<p>For the below code, I am not able to clear the memory allocated for 'root' variable evan after 'del root' and gc.collect(). I understand that in python, garbage collection releases automatically. Is there any way I can clear it more?</p>

<pre><code>from __future__ import with_statement
import os
import sys
from memory_profiler import profile
import gc
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET



def f():
    with open('file.xml') as f:
        output_xml_str = f.read()
    root = ET.fromstring(output_xml_str)
    del root

@profile
def main():
    x = {}
    for i in xrange(10000):
        x[i] = i+1
    del x
    f()
    for i in range(12):
        gc.collect()

if __name__ == "__main__":
    sys.exit(main())
</code></pre>

<p>and here's profiling output</p>

<p><a href="http://i.stack.imgur.com/wNu4E.png" rel="nofollow"><img src="http://i.stack.imgur.com/wNu4E.png" alt="enter image description here"></a></p>

<p>Unfortunately you can't do much except calling <code>gc.collect()</code> plus you can adopt good practice style like you used <code>del</code> to tell the <code>GC</code> that you don't want it anymore so it will be deleted when <code>GC</code> will come around and do it's job.</p>

<p>You should use <code>numpy</code> for container like array which is more efficient in terms of memory management </p>

python python-2.7 python-3.x