Collection Size and Retained Memory

Element count is one part of a collection's memory use. The referenced values and spare storage can also matter.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compare two lists
  2. Measure a meaningful workload
  3. Count or measure the representation as well as values
  4. Distinguish retained data, allocation peaks and processing rate

Compare two lists

A list of one thousand references to one shared object and a list of one thousand distinct populated records have the same length. Their additional retained memory can differ. Mutable names and references explain where the shared object lives in that picture.

Measure a meaningful workload

Compare allocation and peak memory using equivalent input and output rather than length alone. Growing an array can temporarily require extra memory when existing values move. See dynamic array growth for where capacity differs from size.[1]

Count or measure the representation as well as values

A list of a thousand references to one shared string retains one string object through those references. A list of a thousand separately allocated strings can retain much more memory even when the list length is the same. An outer-container size calculation does not automatically include reachable values. Identify whether aliases are shared before summing retained sizes. See repeating sequences.

Distinguish retained data, allocation peaks and processing rate

Grouping a million records into a dictionary can retain full records as well as newly allocated buckets. Summing numeric totals per key can keep state proportional to distinct keys instead. If the source is streamed, peak memory may stay small when each record is discarded after its update. Test a workload with few distinct keys and another with nearly one key per record. See grouped records.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩