⚡️ Speed up function strip_spaces_between_tags by 7%
#127
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.
📄 7% (0.07x) speedup for
strip_spaces_between_tagsindjango/utils/html.py⏱️ Runtime :
810 microseconds→757 microseconds(best of188runs)📝 Explanation and details
The optimization precompiles the regular expression pattern
r">\s+<"into a module-level variable_strip_spaces_patterninstead of compiling it on every function call.What changed:
_strip_spaces_pattern = re.compile(r">\s+<")at module levelre.sub(r">\s+<", "><", str(value))to_strip_spaces_pattern.sub("><", str(value))Why it's faster:
Regular expression compilation is expensive in Python. The original code recompiled the same pattern on every function call, while the optimized version compiles it once when the module is imported and reuses the compiled pattern object. This eliminates the regex compilation overhead from the critical path.
Performance characteristics:
The optimization shows consistent 15-30% speedups across most test cases, with particularly strong gains on simple cases (28-38% faster for empty strings, no tags, etc.) where regex compilation overhead dominates the total runtime. For larger-scale tests with many substitutions, the gains are more modest (1-4%) since the substitution work itself becomes the bottleneck, but the compilation savings still provide meaningful improvement.
This optimization is especially valuable in web frameworks like Django where HTML processing functions are called frequently during request handling.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-strip_spaces_between_tags-mh6sgosdand push.