Skip to content

Latest commit

 

History

History
3 lines (3 loc) · 812 Bytes

File metadata and controls

3 lines (3 loc) · 812 Bytes

2025-03-11 - Optimize dataclass serialization with slots

Learning: dataclasses.asdict can be a significant performance bottleneck when dealing with high-frequency serialization of dataclasses, especially nested ones. For dataclasses that use slots=True (like RequestMetrics), iterating over __slots__ and using getattr to manually construct the dictionary is significantly faster than using asdict. Nested dataclasses can still be supported efficiently by dynamically checking for hasattr(v, '__dataclass_fields__') and falling back to asdict(v) only for the nested components. Action: When optimizing frequent dataclass serialization in Python, check if the dataclass uses slots=True and prefer a custom to_dict method using __slots__ iteration over dataclasses.asdict().