Garbage Collection

Garbage Collection is the reclaiming of unused memory.

Python Example

In Python, memory is managed using a private heap space where all objects and data structures are stored. Memory is recycled using Garbage Collection (gc) which classifies objects into three generations depending on how many collection sweeps they have survived.

  • New objects are placed in the youngest generation (generation 0).

  • If an object survives a collection it is moved into the next older generation.

  • Since generation 2 is the oldest generation, objects in that generation remain there after a collection.

  • In order to decide when to run, the collector keeps track of the number object allocations and deallocations since the last collection.

  • When the number of allocations minus the number of deallocations exceeds threshold0, collection starts.

  • Initially only generation 0 is examined. If generation 0 has been examined more than threshold1 times since generation 1 has been examined, then generation 1 is examined as well.

  • Similarly, threshold2 controls the number of collections of generation 1 before collecting generation 2.

# Import the garbage collection package.
import gc

# Get the configured thresholds.
gc.get_threshold()

# Get the number of objects in each of the generations.
gc.get_count()

# In python, garbage collection is automatic, but can also be done manually.
gc.collect