What is garbage collection in Python?

Max16Neil report abuse

I'm learning Python and sometimes when reading advanced tutorials or documentation, I meet the notion of "garbage collection". What is it?

Answers

ShaDow_ report abuse

It is the process of memory clearing. Your program, when running, uses some memory. During the execution some objects become unneeded. To free memory, Python uses a garbage collector to remove the unneeded objects from memory.

-

Max16Neil report abuse

How the garbage collector knows that the object becomes unneeded?

ShaDow_ report abuse

By looking at the references. If there is no link between this object and any other, then the given object is considered redundant and should be removed from memory.

millykabvy report abuse

I just want to add that sometimes garbage collector is unable to free the memory and then the memory leak emerges in the program. When such a program runs for a long enough period, it consumes more and more memory and your system becomes slower and less productive.

Max16Neil report abuse

It's interesting. Is there any advice about how we can prevent memory leaks?

millykabvy report abuse

The typical reasons for memory leaks include reference cycles and the existing of the continuously growing objects that you forgot to remove after usage. Always remove the object if you don't need to use it further. It is especially true for large global data structures, like lists, or dictionaries, etc. Regarding reference cycles, for example, two objects can be isolated from all other objects but still referencing to each other. In this case, the garbage collector will not remove them. Try to be very careful when referencing objects to each other

ShaDow_ report abuse

I know that there are some tools that can help you with debugging of memory leaks. I have even heard about the package that can draw the graphs to visualize reference cycles (they can be very complicated to detect and understand). Try to search for such a tool when you will need to optimize memory usage.

Max16Neil report abuse

Thank you, it was very interesting!

Add Answer

Need support?

Just drop us an email to ... Show more