TLDR: How Python Handles Integers Under the Hood
Date: 2020-05-17 Source: https://arpitbhayani.me/blogs/python-caches-integers
Overview
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.
Key Points
- 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.
- Reference Counts: Reference count holds the number of different places there are that have a reference to the object.
- 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.