Python memory del list [:] vs list = []

In python, I noticed that if you do

mylist = []

for i in range(0,100000000):
    mylist.append('something here to take memory')

mylist = []

seemingly second call

mylist = []

will delete the link and it will be compiled, but since I look at them, it’s not.

when i use

del mylist[:]

it almost deletes everything except a few megabytes (just looking at the process)

when i use

del mylist[:]
gc.collect()

I seem to be returning to the same amount of memory before the list was created

So why

mylist = []

does not work??? Nothing else refers to it, as far as I can tell

+3
source share
1 answer

How do you rate this?

I did a little test that does not confirm your results. Here is the source:

import meminfo, gc, commands

page_size = int(commands.getoutput("getconf PAGESIZE"))

def stat(message):
    s = meminfo.proc_stat()
    print "My memory usage %s: RSS: %dkb, VSIZE: %dkb" % (
        message, s['rss']*page_size/1024, s['vsize']/1024)
mylist = []

stat("before allocating a big list")
for i in range(0,3000000):
    mylist.append('something here to take memory')

stat("after allocating big list")
### uncomment one of these:
mylist = []
# del mylist[:]
stat("after dropping a big list")
gc.collect()
stat("after gc.collect()")
gc.collect()
stat("after second gc.collect()")
gc.collect()
stat("after third gc.collect()")

The meminfo module used is located here: http://gist.github.com/276090

These are the results with mylist = []:

My memory usage before allocating a big list: RSS: 3396kb, VSIZE: 7324kb
My memory usage after allocating big list: RSS: 50700kb, VSIZE: 55084kb
My memory usage after dropping a big list: RSS: 38980kb, VSIZE: 42824kb
My memory usage after gc.collect(): RSS: 38980kb, VSIZE: 42824kb
My memory usage after second gc.collect(): RSS: 38980kb, VSIZE: 42824kb
My memory usage after third gc.collect(): RSS: 38980kb, VSIZE: 42824kb

del mylist [:]:

My memory usage before allocating a big list: RSS: 3392kb, VSIZE: 7324kb
My memory usage after allocating big list: RSS: 50696kb, VSIZE: 55084kb
My memory usage after dropping a big list: RSS: 38976kb, VSIZE: 42824kb
My memory usage after gc.collect(): RSS: 38976kb, VSIZE: 42824kb
My memory usage after second gc.collect(): RSS: 38976kb, VSIZE: 42824kb
My memory usage after third gc.collect(): RSS: 38976kb, VSIZE: 42824kb

Python , .

+9

Source: https://habr.com/ru/post/1728262/


All Articles