⚡️ Speed up method PhoneNumber._to_dict by 8%
#93
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.
📄 8% (0.08x) speedup for
PhoneNumber._to_dictinweaviate/collections/classes/types.py⏱️ Runtime :
952 microseconds→879 microseconds(best of259runs)📝 Explanation and details
The optimization achieves an 8% speedup by eliminating dictionary mutation and reducing attribute access overhead.
Key changes:
self.default_countryin a local variable instead of accessing it twice, avoiding repeated attribute lookups.Nonecase, reducing code path complexity.Why this is faster:
out["defaultCountry"] = value) requires Python to perform additional internal checks and memory operations compared to direct constructionself.default_country) involves Python's descriptor protocol, so caching it locally saves repeated lookups{"input": ..., "defaultCountry": ...}is more efficient than incremental buildingPerformance characteristics:
The optimization shows particularly strong gains (30-50% faster) when
default_countryis not None, as seen in most test cases. For None cases, the improvement is more modest (8-25%) since the original code already had fewer operations. This makes the optimization especially valuable for typical usage patterns where phone numbers often include country information.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-PhoneNumber._to_dict-mh2z0jtuand push.