⚡️ Speed up method SearchQueryVector.as_dict by 118%
#15
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.
📄 118% (1.18x) speedup for
SearchQueryVector.as_dictinpinecone/db_data/dataclasses/search_query_vector.py⏱️ Runtime :
50.7 microseconds→23.3 microseconds(best of525runs)📝 Explanation and details
The optimization replaces a dictionary comprehension approach with direct conditional assignment, eliminating the overhead of creating an intermediate dictionary and iterating through it.
Key Changes:
Nonevalues using a dictionary comprehensionNoneself.values,self.sparse_values,self.sparse_indices) is accessed only once and stored in a local variablePerformance Benefits:
The line profiler shows the original dictionary comprehension (
{k: v for k, v in d.items() if v is not None}) consumed 60% of the total runtime. This operation involved:d.items()iteratorNoneThe optimized version eliminates this expensive iteration entirely, resulting in a 118% speedup (from 50.7μs to 23.3μs).
Test Case Performance:
The optimization is particularly effective for cases with many
Nonefields - the annotated tests show 158-203% improvements when most or all fields areNone, as the optimized version skips unnecessary dictionary operations entirely.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-SearchQueryVector.as_dict-mh6a4vlnand push.