Meta makes Python 2% slower with Immutable Objects

Meta has recently introduced a groundbreaking concept to Python known as immortal objects. These objects include a special flag that prevents them from being deleted by the garbage collector. By exempting these objects during garbage collection rounds, Python's capabilities are significantly enhanced, offering efficient thread-sharing and over 30% memory savings, as highlighted by Meta's pioneering changes. Learn more about this transformative system design here.

Recently, Meta introduced the concept of immortal objects to Python. The basic idea is to have objects hold a flag stating, "Please don't delete me!"

When a garbage collector does the rounds, it ignores all objects having this flag. And this small change has a big impact on its current and future capabilities.

Objects in Python are augmented with a reference counter. This counter tells you the number of incoming references to an object. A garbage collector iteratively deletes objects which have a reference count equal to zero.

Garbage Collection with Reference Counting
1. Garbage Collection with Reference Counting

Contrast this with Java or Golang, which runs a mark and sweep (Depth First Search) algorithm to find dead objects.

Garbage Collection with Mark and Sweep
2. Garbage Collection with Mark and Sweep

The problem with reference counts is sharing objects across threads. When an object is referenced, the counter increments. This operation is not thread-safe, and needs either of two approaches to work:

  1. Copy on write (create an object copy when adding a reference to it)
  2. Global interpreter lock (Take a lock before making changes)

Both of these approaches have downsides. The first is wasteful, the second is slow.

Instead, Meta's changes help define objects as Immutable. This means that the reference count variables of these objects are also immutable.

Now, the garbage collector can ignore these objects.

Garbage Collection with Immortal Objects
3. Garbage Collection with Immortal Objects

This simple change allows objects to be shared efficiently across threads. The memory savings through this change at Meta are over 30%!

If you want to know more about system design and software engineering, try our system design course at InterviewReady.

Cheers!

Reference: https://engineering.fb.com/2023/08/15/developer-tools/immortal-objects-for-python-instagram-meta

Start Preparing for your Dream Job today!

The most comprehensive Interview prep platform ever built

Start Prep