Python's Base Object Cost: Why Small Ints Take 28 Bytes

Even a simple Python integer like `1` typically occupies 28 bytes on a 64-bit system, comprising 8 bytes each for reference count, type pointer, and size information, plus 4 bytes for the actual value. Floats consume 24 bytes, and an empty string requires 49 bytes of overhead.

The top 3

  1. Python Int's 28-Byte Structure: Ref Count, Type, Value: A small Python integer (like 42) consumes 28 bytes due to its object nature, comprising an 8-byte reference count, an 8-byte type pointer, an 8-byte size field, and 4 bytes for the actual integer value.
  2. Python vs. C++: Integer Memory Footprint Disparity: Unlike C/C++'s primitive, fixed-size integers (e.g., 4 bytes), Python's integers are full-fledged objects, leading to a base 28-byte overhead even for small numbers, a 7x difference compared to a C int.
  3. Python's Integer Interning: Small Number Memory Hack: Python optimizes memory for frequently used integers from -5 to 256 by "interning" them, creating single shared objects to avoid repeated 28-byte allocations and boost performance.

Sources

Open the full topic