Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære sys.getsizeof() and Object Size Inspection | Performance Patterns
Python Memory Management

sys.getsizeof() and Object Size Inspection

Sveip for å vise menyen

sys.getsizeof() is the most direct tool for measuring how much memory a single Python object occupies. Understanding what it measures – and what it does not – prevents common misinterpretations and helps you accurately compare the memory cost of different data representations.

What sys.getsizeof() Measures

sys.getsizeof() returns the size of the object itself in bytes – the object header, internal pointers, and any inline data. It does not include the size of objects the target object references:

1234567891011
import sys # getsizeof measures the container, not its contents price_list = [1500.0, 2300.0, 4100.0, 750.0] print(sys.getsizeof(price_list)) # ~120 bytes – list structure + 4 pointers single_float = 1500.0 print(sys.getsizeof(single_float)) # 24 bytes – one float object # The list does NOT include the floats it points to print(sys.getsizeof(price_list) + 4 * sys.getsizeof(1500.0)) # Closer to true total

Total Size Including References

To measure the true memory footprint of a nested structure, recursively sum all referenced objects:

12345678910111213141516171819202122232425262728
import sys def total_size(obj, seen=None): """Recursively calculate total memory of an object and all it references.""" size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: return 0 seen.add(obj_id) if isinstance(obj, dict): size += sum(total_size(key, seen) + total_size(value, seen) for key, value in obj.items()) elif isinstance(obj, (list, tuple, set, frozenset)): size += sum(total_size(item, seen) for item in obj) return size # Comparing shallow vs total size transaction_record = { "id": "TX_001", "amount": 4500.0, "tags": ["urgent", "international", "flagged"], } print(f"getsizeof only: {sys.getsizeof(transaction_record)} bytes") print(f"Total recursive: {total_size(transaction_record)} bytes")

Comparing Common Structures

1234567891011
import sys import array from collections import deque items = list(range(1000)) print(f"list of 1000 ints: {sys.getsizeof(items)} bytes (container only)") print(f"tuple of 1000 ints: {sys.getsizeof(tuple(items))} bytes") print(f"set of 1000 ints: {sys.getsizeof(set(items))} bytes") print(f"array.array of 1000: {sys.getsizeof(array.array('i', items))} bytes") print(f"deque of 1000 ints: {sys.getsizeof(deque(items))} bytes")

array.array stores values inline – sys.getsizeof() reflects the actual data size. For list, tuple, and set, the reported size is the container overhead plus pointers – the integer objects themselves are counted separately.

String Size Breakdown

Strings in Python carry encoding overhead. The size scales with content:

1234567
import sys print(sys.getsizeof("")) # 49 bytes – empty string overhead print(sys.getsizeof("a")) # 50 bytes – one ASCII character print(sys.getsizeof("hello")) # 54 bytes – 5 ASCII characters print(sys.getsizeof("héllo")) # Larger – non-ASCII forces UCS-2 or UCS-4 encoding print(sys.getsizeof("hello" * 100)) # ~549 bytes – 500 characters

Practical Size Reference

question mark

Why does sys.getsizeof(my_list) not reflect the true memory cost of the list's contents?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 4

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 4. Kapittel 4
some-alt