Python Ints vs. C: Up to 7x Memory Cost

A small Python integer (e.g., 42) consumes at least 28 bytes, while a C `int` typically uses just 4 bytes, showcasing Python's significant memory overhead due to its flexible, arbitrary-precision design and object structure.

The top 3

  1. Python Int's 28-Byte Minimum: The Hidden Components: Even the smallest Python integers consume a minimum of 28 bytes on 64-bit systems, attributed to a fixed overhead that includes an 8-byte reference count, an 8-byte type pointer, an 8-byte object size field, and a 4-byte value storage.
  2. List vs. C Array: Python's Compounded Integer Memory Cost: A Python list of integers incurs significant memory overhead compared to a C array; each list element stores an 8-byte pointer to a separate 28-byte Python integer object, leading to approximately 36 bytes per integer, whereas a C array stores only the raw integer values contiguously.
  3. Arbitrary Precision: Python Ints' Memory Expansion: Python integers support arbitrary precision, meaning they can grow indefinitely, unlike C's fixed-size integers. This flexibility requires dynamic memory allocation and 'size fields' to track their magnitude, increasing memory consumption from 28 bytes to 32 bytes or more for larger values, though small integers (-5 to 256) are cached for efficiency.

Sources

Open the full topic