Archive for December, 2011

Garbage Collection in Python

Saturday, December 24th, 2011

While studying for the final exam in the Fall 2011 Compiler Design course at USF, I decided to investigate garbage collection in my favorite language, Python. Prior to the course I had heard that the CPython interpreter (what the majority purportedly use) uses reference counting for its garbage collector, and to make sure I understood exactly what that means (and its implications) I wrote a quick Python program to illustrate CPython’s inability to collect garbage cycles.

It runs and allows the user to increase the size of allocated memory by fixed amounts (originally 4MiB), then the user can “release” it and turn all memory allocated this way into garbage simultaneously.

It works by creating a doubly-linked list cycle. Even if the program allocates just a single node, it points to itself (twice!), and then extends the cycle with each allocation. You can run this while using a utility like gnome-system-monitor in GNU/Linux in order to see the process memory increasing, and after releasing it, the memory allocation will not drop; the process must be killed to reclaim the memory.

Grab the program here and play around with it yourself.