Trash Talk and Garbage Collection.
Credits: Giphy

Trash Talk and Garbage Collection.


👋 Hi, this is Navjot with a new newsletter. I write about software engineering, best practices, industry standards, and career growth. Thank you for being a reader, and making it a family of over 750 frequent readers with over 200k views.🙏 🎉        

For this newsletter, I have emphasized upon basics of Garbage collection in Python and what life would be like without it.


Garbage collectors are unsung heroes in the world of software development.🫡They are critical for Heap Memory Management and ensuring liveliness by keeping the dynamic memory (Heap) available for the application’s use.

Article content
Memory allocation in a program

The stack segment is used for managing local variables, function arguments, and control information, such as return addresses.

The heap segment provides a flexible area for storing large data structures and objects with dynamic lifetimes. Heap memory may be allocated or deallocated during the program execution.


Heap memory is critical!

In context to Python (if not all programming languages) all non-primitive object information is stored as heaps of memory and the pointer to them is stored as stacks. This includes lists, dictionaries, custom objects, etc etc etc, basically anything apart from integers, float, strings, and booleans.

# Global Variables and Heap Memoy

//list object
num_list = [1,2,3,4,5]
copy_list = num_list        
Article content
Memory allocation for variables

  • The Stack contains a pointer to the data i.e. variables num_list, copy_list
  • The Heap contains the actual data i.e. [1,2,3,4,5]

Variables inside functions?

# Function calls and heap memory

class MyClass:
  def __init__(self,x,y,z):
    self.x=x
    self.y=y
    self.z=z
  def multiply(self):
    return self.x * self.y * self.z

def do_math(x:int,y:int,z:int):
  myclassobj = MyClass(x,y,z)
  product = myclassobj.multiply()
  return product

six = do_math(1,2,3)
print(six)        
Article content
Stack Pileups

Life without garbage collection?

If your application is any bit more complicated than basic computational code you will require Heap Management for sure. Without Garbage Collectors a developer’s life will become messy if not hell.

Article content
Certain Death for Heap

Life without a Garbage Collector will

  • Require a developer to manually clean up memory by deleting all pointers to the data.
  • This will create infinite situations of memory leak
  • Creating and managing complicated Objects and Classes would be a mess.

Garbage collection triggers

All Garbage Collectors generally work on similar guidelines and are triggered at

  • Certain time intervals (at 10 seconds or so)
  • Certain Thresholds are crossed for memory usage (percentage of Total available memory)
  • As soon as a certain amount (>=5) of references are available to be cleaned


Some Dry Run?

Just like any other programming language, Garbage Collector in Python is built and runs automatically in the background. The way garbage collection works is simple.

Article content
Garbage collection flow

  • It keeps a reference count of all variables accessing the data as shown in the diagram currently referenced by 2.
  • As soon as the reference pointer ie the variables are deleted or exit the scope the reference count is dropped by 1.
  • As soon as the heap data becomes a dangling resource it’s deleted.

Cleanup in function scopes

# Function calls and heap memory

class MyClass:
  def __init__(self,x,y,z):
    self.x=x
    self.y=y
    self.z=z
  def multiply(self):
    return self.x * self.y * self.z

def do_math(x:int,y:int,z:int):
  myclassobj = MyClass(x,y,z)
  product = myclassobj.multiply()
  return product

six = do_math(1,2,3)
print(six)        
Article content
Heap Cleanup in function calls

As soon as the function call is complected and stack pop happens the object MyClass has 0 reference and is cleaned up by Garbage Collector immediately making space for other object creations.


TLDR

Memory allocation deallocation and reference in Heap memory is costly as compared to stacks. All garbage collectors are designed efficiently to not block application runtime and utilize independent thread or empty flock cycles to run the cleanup job.

You would never be required to alter the behavior of the GCs but knowing it's functionality will always help you create efficient and clean applications.

For Daredevils

If you feel like exploring what happens without garbage collection in the entry point of your python application add two lines of code and see the magic

// main.py

import gc
gc.disable()        

PS: I hope the article had some valuable insights. If you have any queries feel free to comment down below. Till next time 👋.

To view or add a comment, sign in

More articles by Navjot Bansal

Insights from the community

Others also viewed

Explore topics