sys.getsizeof() and Object Size Inspection
Stryg for at vise menuen
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:
1234567891011import 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:
12345678910111213141516171819202122232425262728import 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
1234567891011import 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:
1234567import 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
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
sys.getsizeof() and Object Size Inspection
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:
1234567891011import 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:
12345678910111213141516171819202122232425262728import 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
1234567891011import 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:
1234567import 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
Tak for dine kommentarer!