Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Memory & performanceSeniorOccasionalPerformance

Beyond `__slots__`, what other techniques reduce memory usage for large collections of data in Python?

Answer

The `array` module stores a large sequence of a single primitive numeric type in a compact, C-style contiguous buffer instead of as individual boxed Python objects, dramatically cutting memory versus a `list` of a million separate `int` objects. Generators, discussed elsewhere for laziness, also reduce peak memory because they never materialize the entire sequence at once. For structured records, `__slots__` (or `@dataclass(slots=True)` since Python 3.10) removes each instance's per-object `__dict__` overhead, and for genuinely numeric workloads, NumPy arrays store elements in a single packed buffer with far less per-element overhead than any pure-Python container.

Strong answer includes

  • array module packs primitives into a compact contiguous buffer
  • generators avoid materializing the whole sequence at once
  • slots (or dataclass slots=True) and NumPy arrays cut per-element overhead

Practical example

Storing ten million sensor readings as

Python example
array.array("d", readings)

uses roughly eight bytes per value, while a plain `list` of Python `float` objects uses several times more due to per-object overhead and pointer indirection.

#performance#memory-management

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modulesdataclasses — Data ClassesPython Software Foundation · Generated dunder methods, field defaults and frozen/eq/order semantics