Memory and CPython #5.1
CPython reclaims most objects by counting references. Its garbage collector can also reclaim objects that keep each other alive in a cycle.
When does an object get reclaimed?
What does this code print after it deletes the name messages?
messages = ["Orbit"]
queue = [messages]
del messages
print(queue[0])
# prints: ['Orbit']
del messages removes the binding between a name and its object. The first element of queue still holds the list. CPython, the reference implementation of Python, counts the references that keep objects alive. We'll follow an object to the end of its life, then look at when the cost of running Python code matters to a request.
| Section | Example | Result |
|---|---|---|
| The last reference | del messages | queue[0] still works |
| Reference cycles | node.next = node | The object holds itself |
| Computing and waiting for I/O | 990 + 10 // 2 | 995 ms |
How some other languages compare
| Language | Reclaiming objects | Running code |
|---|---|---|
| Python (CPython) | Reference counting, reclaimed as soon as no reference is left; a GC for cycles | Interprets bytecode |
| JavaScript (V8) | Tracing GC, reclaimed when the GC runs | JIT to machine code |
| Java (HotSpot) | Tracing GC (G1 by default) | JIT to machine code |
| Go | Mark-and-sweep GC running alongside the program | Compiled ahead to machine code |
The last reference
Reading from queue told us the list was still alive. How can we also tell when an object is gone? A weak reference lets us check on an object without keeping it alive. For this example we'll use an instance of an empty class, Message, which supports weak references.
| Syntax | Meaning |
|---|---|
pass | Leave the class body empty |
ref(message) | Create a weak reference to the message |
watch() | Return the object if it is alive, or None once it has been reclaimed |
from weakref import ref
class Message:
pass
message = Message()
queue = [message]
watch = ref(message)
del message
print(watch() is queue[0])
# prints: True
queue.clear()
print(watch() is None)
# prints: True
At the first print, queue still holds a strong reference to the message. When clear() removes the last element, the strong reference count reaches zero. The standard CPython build with the global interpreter lock (GIL) reclaims an ordinary object like this one immediately.
Reference cycles
What if an object points back to itself? The next attribute below still holds a strong reference after the name node is gone.
import gc
from weakref import ref
class Node:
pass
node = Node()
node.next = node
watch = ref(node)
print(node.next is node)
# prints: True
del node
gc.collect()
print(watch() is None)
# prints: True
The node's reference count stays above zero because of next. Yet no path of strong references leads into the cycle from the rest of the program. CPython's cyclic garbage collector (GC) can identify and reclaim cycles like this one. It normally runs automatically. Calling gc.collect() ensures a collection has run by the time we check the weak reference.
Computing and waiting for I/O
CPython normally compiles source code to bytecode, instructions its interpreter executes. A loop that adds numbers in Python repeatedly performs addition on objects whose types are determined at runtime. That cost adds up when computation takes most of the time (a CPU-bound workload).
Suppose a request spends 10 milliseconds (ms) computing locally, then waits 990 ms for a large language model (LLM) API to respond. How much time would doubling the speed of the local computation save? Here floor division gives exactly 5 ms for 10 // 2.
compute_ms = 10
wait_ms = 990
print(wait_ms + compute_ms)
# prints: 1000
print(wait_ms + compute_ms // 2)
# prints: 995
The request finishes only 5 ms sooner. When a request spends most of its time waiting for data (an I/O-bound workload), measure the wait separately from computation before optimizing the loop.
Key takeaways
- CPython counts strong references. After you delete the last name, a list element or an attribute can still hold the object.
- The garbage collector can reclaim a reference cycle once the program has no path into it.
- Speeding up local code reduces only the part of a request spent executing that code.
