Optimizing `INCREF`/`DECREF`: Borrowing & Immortals

Recent Python versions have introduced optimizations to mitigate `Py_INCREF`/`Py_DECREF` overhead: Python 3.14 added `LOAD_FAST_BORROW` bytecode to avoid incrementing reference counts for local variable loads in hot loops, and Python 3.12 introduced 'immortal objects' to bypass reference count checks for frequently used, never-deallocated objects.

The top 3

  1. Python 3.14's LOAD_FAST_BORROW: Zero-Cost Locals: Python 3.14 introduced the `LOAD_FAST_BORROW` bytecode instruction, utilizing static lifetime analysis to eliminate `Py_INCREF` operations when loading local variables, thereby significantly reducing reference counting overhead in performance-critical loops.
  2. Python 3.12's Immortals: Singletons Skip Ref-Counting: Beginning with Python 3.12 (PEP 683), objects such as `None`, `True`, `False`, and small integers are marked as 'immortal,' meaning their reference counts are fixed to a special value, allowing `Py_INCREF`/`Py_DECREF` functions to bypass them entirely, enhancing performance and enabling true immutability.
  3. Ref-Count Evolution: Paving Way for Free-Threading: The ongoing evolution of CPython's reference counting, through innovations like borrowing and immortal objects, significantly reduces `Py_INCREF`/`Py_DECREF` overhead and contention. These advancements, coupled with techniques like deferred reference counting and stack references, are crucial building blocks towards achieving a more efficient, multi-core, and free-threaded Python runtime.

Sources

Open the full topic