3.3 Garbage Collection

A *Literal* Garbage Collector

Figure 3.2: A Literal Garbage Collector

Garbage collection is a process whereby programs (i.e., Python) attempt to free up memory that is no longer being used by objects.

3.3.1 Garbage collection in more detail

Whenever you do something like x = 123 in your Python console, your machine stores the variable x into its memory. When x is finally called somewhere in your program, your machine will then retrieve the value of x (and do whatever it is that you wanted to do with it).

Way back in the days, developers had to be responsible for managing memory in their systems. So, this implied that one would first have to (somehow) allocate enough memory for an object first before finally deallocating the memory to “free it up”. Needless to say, there were two major problems with this approach:

  1. Forgetting to free up memory can lead to memory leaks

    A memory leak is a bug that causes a program to continually use memory (i.e., RAM) without freeing it up. Consequently, this can potentially lead to slow (computer and software) performances and your program(s) crashing!

  2. Freeing up memory at the wrong times can crash your programs

    If you free up memory too soon (i.e., before your program is done using it), your program(s) can potentially crash when it tries to access a value that doesn’t exist! When a variable references a location in memory that has been freed, the variable is called a dangling pointer.

    Note that a pointer refers to a specific location in your machine’s memory.

Nonetheless, newer languages like Python, Ruby, R, and Golang have included automatic memory management: hence - enter the garbage collector - a background process that manages memory allocation for you!

3.3.2 Garbage collection in Python?

I will admit: I am no expert on garbage collection (i.e., I merely know about it, but I don’t fiddle around with Python’s garbage collector). However, the gc module in Python’s standard library allows you to manipulate the garbage collector should you ever have a need to.

For this reason, you can read up more on garbage collection in the link that I proposed in the group chat: https://stackify.com/python-garbage-collection/.

However, unless you have good reason to, I’d suggest leaving Python’s garbage collector alone (i.e., Python already does a good enough job clearing up memory for you - the developer). However, for all intents and purposes, you would likely do good to check out the link above if you are planning to go down this path!