November 6, 2025
Heap it real
How often does Python allocate?
Yes, Python numbers are “fancy objects”—and the comments are pure chaos
TLDR: Python stores numbers as full objects, so printing lots of them triggers tons of allocations, while pure addition is somewhat optimized. Comments exploded into a brawl: some said “that’s Python,” others flaunted Julia and C speed, and one link hinted CPython may soon make small numbers cheaper.
A dev poked Python’s brain and found that even tiny numbers live like VIPs: each integer is a full-blown object on the heap. Printing 100,000 numbers led to over 100k “ALLOCATING” messages, but just adding numbers in a loop dropped it to ~905—cue performance panic and meme frenzy. The “this is fine” crowd, led by folks like nu11ptr, shrugged: in Python, everything is an object, that’s the point. Meanwhile, speed evangelists rolled in with Julia slides bragging “60x faster,” and C loyalists flexed: in C, you always know what’s allocating. Others tried to calm the fire: zahlman reminded everyone CPython (the main Python) is just one flavor; other versions like PyPy or Jython may behave differently. Then sushibowl dropped a tease—CPython might add tagged pointers, a trick to make small numbers cheaper—which sent optimists into “maybe soon!” mode while skeptics yelled “I’ll believe it when NumPy stops carrying my workflow.” Jokes flew fast: “every number is a diva,” “print() allocates for attention,” and “Python integers live in luxury condos.” The thread turned into a reality show: Team Dynamic vs Team Speed vs Team “use another runtime.” And yes, everyone kept posting benchmarks like they were zodiac signs.
Key Points
- •In CPython, integers are represented as heap-allocated PyLongObject*.
- •Instrumentation of long_alloc showed 100,904 allocations when printing i + 1 in a 100,000-iteration loop.
- •Performing integer addition without printing (a = i + 1) led to only 905 allocations over 100,000 iterations.
- •CPython’s long_add uses compact integer checks and _PyLong_FromSTwoDigits, which can return preallocated small-int objects.
- •PyLongObject stores digits in base 2^30, and stwodigits is used to hold intermediate results of addition.