⚡️ Speed up method Urlizer.is_email_simple by 27%
#129
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.
📄 27% (0.27x) speedup for
Urlizer.is_email_simpleindjango/utils/html.py⏱️ Runtime :
7.18 milliseconds→5.64 milliseconds(best of37runs)📝 Explanation and details
The optimization introduces validator instance caching to avoid repeatedly creating
EmailValidatorobjects. In the original code,EmailValidator(allowlist=[])creates a new validator instance on every call tois_email_simple(). The optimized version creates the validator only once and stores it as a class attribute_email_validator, reusing it for all subsequent calls.Key changes:
hasattr()to create the validator only onceUrlizer._email_validatorclass attributeWhy this improves performance:
Object instantiation in Python has overhead - creating a new
EmailValidatorinvolves initializing its internal state, compiling regex patterns, and setting up validation logic. By caching the validator instance, this initialization cost is paid only once instead of on every function call.The line profiler shows the optimization is most effective when
is_email_simple()is called repeatedly - the 27% overall speedup comes from eliminating redundant validator instantiation. Test results demonstrate this scales well:This optimization is particularly valuable for applications that validate many email addresses in sequence, such as bulk email processing or form validation systems.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Urlizer.is_email_simple-mh6swoshand push.