⚡️ Speed up function convert_camel_case_resource_noun_to_snake_case
by 13%
#36
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.
📄 13% (0.13x) speedup for
convert_camel_case_resource_noun_to_snake_case
ingoogle/cloud/aiplatform/utils/__init__.py
⏱️ Runtime :
4.06 milliseconds
→3.60 milliseconds
(best of164
runs)📝 Explanation and details
The optimized code achieves a 12% speedup by pre-compiling the regex pattern at module scope instead of compiling it on every function call.
Key optimization:
_CAMEL_TO_SNAKE_RE = re.compile(r"([A-Z]+)")
is created once when the module loads, rather than callingre.sub("([A-Z]+)", ...)
which compiles the pattern every time the function runs.Why this improves performance:
In Python's
re
module, every call tore.sub()
with a string pattern must first compile that pattern into a regex object. By pre-compiling the pattern once and reusing the compiled object via_CAMEL_TO_SNAKE_RE.sub()
, we eliminate this repeated compilation overhead.The line profiler shows the regex substitution line dropped from 11.9ms to 10.2ms (14% reduction), which represents 93% of the original function's total time. This optimization is particularly effective because:
([A-Z]+)
is used repeatedly across all function callsTest case benefits:
The optimization maintains identical behavior while providing consistent performance gains across all input types.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-convert_camel_case_resource_noun_to_snake_case-mgkkldbs
and push.