What is garbage collection in Python?
I'm learning Python and sometimes when reading advanced tutorials or documentation, I meet the notion of "garbage collection". What is it?
I'm learning Python and sometimes when reading advanced tutorials or documentation, I meet the notion of "garbage collection". What is it?
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.
-
How the garbage collector knows that the object becomes unneeded?
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.
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.
It's interesting. Is there any advice about how we can prevent memory leaks?
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
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.
Thank you, it was very interesting!
Just drop us an email to ... Show more