⚡️ Speed up function superreload by 99%
#468
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.
📄 99% (0.99x) speedup for
superreloadinmarimo/_runtime/reload/autoreload.py⏱️ Runtime :
9.75 seconds→4.91 seconds(best of5runs)📝 Explanation and details
The optimized code achieves a 98% speedup through several key optimizations that reduce redundant operations and expensive attribute lookups:
Key Optimizations:
Eliminated Double Weakref Insertion: The original code redundantly called
old_objects.setdefault(key, []).append(weakref.ref(obj))both insideappend_obj()and immediately after in thesuperreload()loop. The optimization removes this duplication, cutting the weakref creation overhead in half.Reduced Attribute Lookups: Added local variables
module_dict = module.__dict__andmod_name = module.__name__to cache frequently accessed attributes. The profiler shows these lookups were happening thousands of times per reload.Optimized Dictionary Access Pattern: Replaced the
key not in old_objects+old_objects[key]pattern withold_objects.get(key), eliminating redundant dictionary lookups.Removed Unnecessary List Creation: Changed
list(module.__dict__.items())tomodule.__dict__.items()since the dictionary isn't modified during iteration, avoiding unnecessary list allocation.Improved hasattr Pattern: Replaced
hasattr(obj, "__module__") and obj.__module__ == module.__name__withgetattr(obj, "__module__", None) == module.__name__, which is more efficient and handles missing attributes gracefully.Performance Impact by Test Scale:
The optimizations are particularly effective for large-scale test cases because they eliminate O(n) redundant operations that compound significantly as module size increases. The
update_genericfunction, which consumes 99% of runtime, benefits from receiving fewer duplicate calls due to the eliminated double-insertion.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-superreload-mhb0qrp1and push.