`del` variable, memory-wise?

If a variable is only used in one-third of my code, should I delete it in the remaining two-thirds for memory optimization?

We don’t know whether you have a memory problem…

1 Like

Is it practical to delete the value of a variable to reduce memory consumption, or are there benefits to doing so?

The most important thing to understand about del is that it doesn’t delete anything. (Ok, this isn’t true. It deletes the name you give it, but the object the name refers won’t have been freed if anything else refers to it.)

The point of @pochmann’s oblique observation is that it’s a waste of your valuable time to solve problems you don’t have. It isn’t usually necessary to free up objects explicitly.

If the object is large enough to be a problem then yes, it is worth explicitly dropping the reference you have to it, with del or otherwise. A good way to do this is to break up your program into functions. The large object could then be a local variable inside a function you call to do that one third of your program. You can see more easily whether you have created any more references to it, and it will evaporate automatically when the function returns.

3 Likes

Unless the value is huge you will see nothing happen.
Even if python free’s the memory the C runtime memory management is unlikely to be able to give the memory back the operating system.

2 Likes

Good point. I think we know it doesn’t. So it could only benefit you if you had to create some more big objects subsequently in the program.

Glibc malloc arena can be given back to linux if all the alloc’s in the arena are free I think.
But that is very unlikely in any real world program.

1 Like