1.

What is garbage collection? How does it work in Python?

Answer»

Garbage COLLECTION is the mechanism of freeing up a computer’s memory by identifying and disposing of those objects that are no longer in use. C and C++ language compilers don’t have the capability of automatically disposing memory contents. That’s why disposal of memory resources has to be manually performed. Runtime environments of Java and Python have automatic garbage collection feature hence they provide efficient memory management.

Garbage collection is achieved by using different strategies. Java uses a tracing strategy WHEREIN it determines which objects should be ADDED to the garbage, by tracing the objects that are reachable by a chain of references from certain root objects. Those that are not reachable are considered as garbage and collecting them.

Python on the other hand uses a reference counting strategy. In this case, Python keeps COUNT of the number of references to an object. The count is incremented when a reference to it is created, and decremented when a reference is destroyed. Garbage is identified by having a reference count of zero. When the count reaches zero, the object's memory is reclaimed.

For example 0 is stored as int object and is assigned to variable a, thereby incrementing its reference count to 1. However, when a is assigned to another object, the reference count of 10 becomes 0 and is eligible for garbage collection.

Python’s garbage collector works periodically. To identify and collect garbage manually, we have gc module in Python’s library.  You can also set the collection threshold value. Here, the default threshold is 700. This means when the number of allocations vs. the number of deallocations is greater than 700, the automatic garbage collector will run.

>>> import gc >>> gc.get_threshold() (700, 10, 10)

The collect() FUNCTION identifies and collects all objects that are eligible.



Discussion

No Comment Found