⚡️ Speed up function get_runner by 79%
#112
Open
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.
📄 79% (0.79x) speedup for
get_runnerindjango/test/utils.py⏱️ Runtime :
813 microseconds→455 microseconds(best of71runs)📝 Explanation and details
The optimization adds a module caching check using
sys.modules.get()before calling the expensive__import__()function.Key changes:
import sysat the toptest_module_namealready exists insys.modulescache__import__()if the module isn't already loadedWhy this is faster:
The line profiler shows that
__import__()was the bottleneck, consuming 73% of execution time in the original code. Python's__import__()function performs file system operations, module compilation, and initialization - even for already-loaded modules. By checkingsys.modulesfirst (a simple dictionary lookup), we avoid this expensive operation when the module is already in memory.Performance impact by test case:
The optimization is most effective for Django test scenarios where the same test runner classes are imported repeatedly across multiple test runs.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_runner-mh6jwhvjand push.