⚡️ Speed up function camel_to_kebab by 11%
#20
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.
📄 11% (0.11x) speedup for
camel_to_kebabinpanel/util/__init__.py⏱️ Runtime :
12.3 milliseconds→11.1 milliseconds(best of110runs)📝 Explanation and details
The optimization replaces repeated
re.sub()calls with pre-compiled regex patterns stored as module-level constants. Instead of compiling the same regular expressionsr'([a-z0-9])([A-Z])'andr'([A-Z]+)([A-Z][a-z0-9])'on every function call, the patterns are compiled once at module import time and reused.Key changes:
_pattern1 = re.compile(r'([a-z0-9])([A-Z])')and_pattern2 = re.compile(r'([A-Z]+)([A-Z][a-z0-9])')at module levelre.sub()calls with_pattern1.sub()and_pattern2.sub()using the pre-compiled patternsWhy this is faster:
Regular expression compilation is expensive in Python. The original code recompiles both patterns every time
camel_to_kebab()is called, while the optimized version compiles them once and reuses the compiled pattern objects. Pre-compiled patterns have faster.sub()methods since they skip the compilation step entirely.Performance characteristics:
The line profiler shows the first regex operation improved from 13,719ns to 12,421ns per hit (9.5% faster) and the second from 4,267ns to 3,127ns per hit (26.7% faster). The optimization provides consistent 10-27% speedups across all test cases, with particularly strong gains on simple inputs like single words and basic camel case conversions. For large-scale operations with many function calls, the cumulative savings from avoiding repeated regex compilation becomes substantial, as seen in the batch processing test showing 23% improvement.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-camel_to_kebab-mha4wbwsand push.