How does Python handle the Memory of Immutable types?

27/06/2024 0 By indiafreenotes

In Python, memory management for immutable types is handled with specific strategies to optimize performance and minimize memory usage. Immutable types in Python include int, float, str, tuple, frozenset, and bytes.

Key Characteristics of Immutable Types

  1. Immutability:
    • Immutable objects cannot be changed after they are created. Any modification results in the creation of a new object.
    • Example: If you concatenate two strings, a new string object is created rather than modifying the original strings.
  2. Interning:
    • For certain immutable types, Python employs interning to save memory and speed up execution. Interning is the practice of storing only one copy of an immutable object and reusing it.
    • Example: Small integers (typically in the range of -5 to 256) and commonly used strings are interned. This means that two variables referencing the same small integer or string will point to the same memory location.

a = 256

b = 256

print(a is b)  # Output: True

 

Memory Handling for Different Immutable Types

  1. Integers (int):
    • Small integers are interned and reused. For integers outside this range, new objects are created as needed.
    • Python uses a pool of preallocated integer objects for small integers to optimize memory usage and performance.
  2. Strings (str):

    • Strings that are compile-time constants or frequently used are interned. This includes string literals and identifiers.
    • When you perform operations that produce a new string (like concatenation), a new string object is created, and the old strings remain unchanged.
  3. Tuples (tuple):

    • Tuples are immutable sequences. When you create a tuple, Python allocates memory for the entire tuple at once.
    • If you need to modify a tuple, a new tuple must be created with the desired changes, which results in a new memory allocation.
  4. Floating Points (float):

    • Floats are typically not interned. Each float value is a distinct object in memory.
    • When you perform operations involving floats, new float objects are created as needed.
  5. Frozensets (frozenset):

Frozensets are immutable sets. Memory allocation for a frozenset happens at creation, and like other immutable types, any modification results in the creation of a new frozenset.

  1. Bytes (bytes):

Bytes objects are immutable sequences of bytes. Like strings, operations on bytes that produce new byte sequences result in new objects being created.

Memory Efficiency Strategies

  1. Reusing Objects:

    • Python reuses existing immutable objects wherever possible to save memory. For example, small integers and short strings are reused.
    • This reuse is implemented internally and is transparent to the user.
  2. Garbage Collection:

    • Python uses reference counting as the primary garbage collection mechanism. When an immutable object’s reference count drops to zero, the memory it occupies is deallocated.
    • For cyclic references, Python employs a garbage collector that can detect and clean up circular references, though this is more relevant for mutable objects.
  3. Optimization by Compilers and Interpreters:

Python compilers and interpreters may perform various optimizations for immutable objects. For example, expressions involving constants may be precomputed.

Example of Immutable Memory Handling:

# Integer interning example

a = 1000

b = 1000

print(a is b)  # Output: False (because 1000 is not interned)

# String interning example

s1 = “hello

s2 = “hello

print(s1 is s2)  # Output: True (because the string “hello” is interned)

# Tuple immutability example

t1 = (1, 2, 3)

t2 = t1 + (4,)

print(t1)  # Output: (1, 2, 3)

print(t2)  # Output: (1, 2, 3, 4)