How to Manage Memory with Garbage Collection
Garbage Collection
is a memory management system that automatically manages and removes objects that are no longer in use (unreferenced memory).
Memory is the space where data is stored in a computer. The data needed while a program is running is stored in memory, and once the program ends, the data stored in memory is deleted.
Garbage collection plays an important role in preventing memory leaks
and improving the efficiency of a program's memory usage.
When a Class Stores Variables
When a class stores a variable, the object it references remains in memory.
This object remains in memory until it becomes eligible for garbage collection when the variable is no longer needed.
class MyClass:
def __init__(self, data):
self.data = data
# Creating and referencing the object
obj = MyClass([1, 2, 3])
In this example, the obj
object references an instance of MyClass
, storing the list [1, 2, 3]
in the data
variable. As long as obj
exists, garbage collection will not reclaim this object.
When a Class Does Not Store Variables
If a class does not store variables, garbage collection will automatically reclaim the instance from memory when there are no more references to the object.
class MyClass:
pass
# Creating and referencing the object
obj = MyClass()
# Removing the reference
del obj # Target for garbage collection
In this example, obj
references an instance of MyClass
.
When del obj
is called to remove the reference, garbage collection can reclaim the MyClass
instance.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.