⚡️ Speed up function encode_query by 18%
#153
Open
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.
📄 18% (0.18x) speedup for
encode_queryinskyvern/client/core/query_encoder.py⏱️ Runtime :
5.31 milliseconds→4.51 milliseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 17% speedup through several targeted micro-optimizations that reduce Python's function call overhead and attribute lookups:
Key Optimizations:
Local Variable Caching: Stores frequently-used functions (
isinstance,pydantic.BaseModel) and methods (append,extend) in local variables, eliminating repeated global/attribute lookups during tight loops.Restructured Control Flow: Separates the
pydantic.BaseModelanddictcases into distinctif/elifbranches instead of using compound conditions, reducing redundantisinstancecalls and enabling early returns viatraverse_query_dict.Method Reference Caching: Pre-fetches
encoded_values.appendandencoded_values.extendmethod references outside the loop, avoiding attribute lookups on every iteration.Performance Impact by Workload:
Critical Usage Context:
This function is called in the HTTP client's hot path for every API request to encode query parameters. Given that web applications typically make many requests, even a 17% improvement compounds significantly. The optimization particularly benefits scenarios with complex nested data structures or large collections - common in API parameter encoding.
The changes maintain identical behavior while being especially effective for the large-scale test cases that mirror real-world API usage patterns.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-encode_query-mjapw83land push.