⚡️ Speed up function require_jinja2 by 6%
#116
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.
📄 6% (0.06x) speedup for
require_jinja2indjango/test/utils.py⏱️ Runtime :
324 microseconds→304 microseconds(best of556runs)📝 Explanation and details
The optimization extracts the static
TEMPLATESlist configuration to a module-level constant, eliminating redundant dictionary construction on every function call.Key changes:
TEMPLATESlist from inside the function to module-level as a constantWhy this improves performance:
The original code reconstructs the same 2-element list containing identical dictionary objects every time
require_jinja2is called. Each dictionary construction involves multiple key-value assignments and list allocation. The line profiler shows significant time spent on lines creating the dictionaries (lines with{, string assignments, etc.).By pre-computing this static configuration once at module load time, each function call now simply references the existing objects rather than recreating them. This eliminates:
The 6% speedup is most pronounced when
require_jinja2is called frequently, as shown in the test cases that decorate 100+ functions. For single-use scenarios, the improvement is minimal, but for repeated decorator applications (common in test suites), the cumulative savings become significant.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-require_jinja2-mh6l1ygband push.