How Python Handles Integers Under the Hood
Source: https://arpitbhayani.me/blogs/python-caches-integers Date: 2020-05-17
Dive into Python's integer implementation! Explore how singletons and reference counting optimize performance for small integers.
An integer in Python is not a traditional 2, 4, or 8-byte implementation but rather it is implemented as an array of digits in base 2^30 which enables Python to support super long integers. Since there is no explicit limit on the size, working with integers in Python is extremely convenient as we can carry out operations on very long numbers without worrying about integer overflows. This convenience comes at a cost of allocation being expensive and trivial operations like addition, multiplication, division being inefficient.
Each integer in python is implemented as a C structure illustrated below.
