⚡️ Speed up method _ImportHookChainedLoader._load_module by 333%
#79
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.
📄 333% (3.33x) speedup for
_ImportHookChainedLoader._load_moduleinwandb/sdk/lib/import_hooks.py⏱️ Runtime :
543 microseconds→126 microseconds(best of101runs)📝 Explanation and details
The optimized code achieves a 332% speedup through three key micro-optimizations that eliminate expensive operations:
1. Eliminated Class Instantiation Overhead (84% reduction in
_set_loader)UNDEFINEDclass on every call (class UNDEFINED: pass)object()sentinel (_UNDEFINED = object())_set_loadertime). Usingobject()reduces this to 38,253ns - a 94% reduction in sentinel creation overhead.2. Reduced Dictionary Operations in Hook Processing
_post_import_hooks.pop(name, {})which creates an empty dict when no hooks exist_post_import_hooks.pop(name, None)and early returns if no hooks3. Optimized Attribute Access Pattern
getattrcalls with complex boolean logic__spec__and itsloaderproperty.Performance Results by Test Type:
__loader__or__spec__attributesThe optimizations are most effective for workloads with frequent module loading where hooks are rarely registered, as the code now short-circuits expensive operations early.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_ImportHookChainedLoader._load_module-mhdsc6lmand push.