Deleting objects on the fly

Campbell Barton cbarton at metavr.com
Fri Aug 10 05:54:58 EDT 2007


Michele Simionato wrote:
> On Aug 10, 2:25 am, Godzilla <godzillais... at gmail.com> wrote:
>> Hello,
>>
>> I wish to know whether I should delete objects created on the fly via
>> the "del obj" statement. I noticed the RAM usage increased whenever
>> the application is being run for a long time. I am creating lots of
>> objects (messages) on the fly for communication between threads.
>>
>> Rather than having python's gc to do the work, does it make a
>> difference if I force a deletion?
>>
>> Thanks.
> 
> Probably not, 'del x' just decrements the reference count, but
> it is the gc who does the real job. See http://docs.python.org/ref/customization.html#l2h-175
> 
> Do you have reference cycles in your application? You should
> tell us something more.
> 
>        Michele Simionato
> 

del x will remove x from memory if nothing else is refering to it, but 
this dosnt really take the load off the GC since the GC will still check 
the references and remove if there are none.

In some cases you could use to save ram...

a = 'really big string'
...do stuff with a...
del a

b = 'another really big string'
...do stuff with b...
del b


in the case that 'a' is not needed, after its used, and you dont want to 
re-use the variable name. then del will free some ram since they both 
wont need to exist at the same time.

WHen I say free ram, python its self will probably keep the ram for 
later use but at least it wont need a and b in memory at once, so its 
likely not to use as much ram.

But be careful using del in a loop since it can slow things down, its 
like adding and removing an item from a dictionary many times. your 
better off just redefining that variable or using del after the loops 
finished.




More information about the Python-list mailing list