⚡️ Speed up function sanitize_relationship_for_cypher by 22%
#27
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.
📄 22% (0.22x) speedup for
sanitize_relationship_for_cypherinmem0/memory/utils.py⏱️ Runtime :
2.59 milliseconds→2.11 milliseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 22% speedup by eliminating redundant work and leveraging more efficient Python operations. Here are the key optimizations:
1. Moved expensive setup outside the function: The original code recreated the 37-key
char_mapdictionary on every function call (31.4% of runtime). The optimized version moves this to module level, eliminating this overhead entirely.2. Pre-compiled regex pattern: Instead of compiling
r"_+"on each call (24.2% of original runtime), the pattern is compiled once at module level as_re_sub_underscores.3. Optimized character replacement strategy:
"...") are handled first withstr.replace()to avoid conflictsstr.translate()with a pre-built translation table, which is significantly faster than iterating through individualstr.replace()calls4. Reduced iteration overhead: The original code performed 37 individual
str.replace()operations (23% of runtime). The optimized version does just 2 multi-character replacements plus one efficienttranslate()call.Performance characteristics by test type:
The optimization is most beneficial for typical use cases with shorter strings and moderate special character density, which appear to be the common case based on the test results showing consistent 2-4x speedups for basic scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sanitize_relationship_for_cypher-mhlpkz7wand push.