⚡️ Speed up method _BackupLocationConfig._to_dict by 857%
#98
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 857% (8.57x) speedup for
_BackupLocationConfig._to_dictinweaviate/backup/backup_location.py⏱️ Runtime :
230 microseconds→24.0 microseconds(best of98runs)📝 Explanation and details
The optimization replaces Pydantic's
model_dump(exclude_none=True)method with a direct dictionary comprehension that filters out None values fromself.__dict__. This achieves an 856% speedup by eliminating the overhead of Pydantic's serialization machinery.Key changes:
model_dump()call: Pydantic'smodel_dump()performs validation, type checking, and handles complex serialization scenarios, which adds significant overhead for simple field access__dict__access: Uses{k: v for k, v in self.__dict__.items() if v is not None}to directly access the instance's attribute dictionary and filter out None valuescast(): The dictionary comprehension already returns the correct typeWhy this is faster:
Pydantic's
model_dump()is designed for complex serialization scenarios (nested models, custom serializers, aliases, etc.) but comes with substantial overhead. For simple filtering of None values, direct dictionary access bypasses all this machinery and operates at native Python speed.Test case performance:
The optimization excels across all scenarios:
This optimization is particularly effective for models with simple field types that don't require Pydantic's advanced serialization features, which appears to be the primary use case based on the test results.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_BackupLocationConfig._to_dict-mh32m6j3and push.