⚡️ Speed up method SharedObjectLoadingScope.__enter__ by 9%
#208
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.
📄 9% (0.09x) speedup for
SharedObjectLoadingScope.__enter__inkeras/src/legacy/saving/serialization.py⏱️ Runtime :
1.57 milliseconds→1.44 milliseconds(best of250runs)📝 Explanation and details
The optimization eliminates a function call overhead by inlining the
getattroperation directly in the__enter__method instead of calling_shared_object_disabled().Key Changes:
if _shared_object_disabled():withdisabled = getattr(SHARED_OBJECT_DISABLED, "disabled", False)followed byif disabled:Why This Improves Performance:
In Python, function calls have inherent overhead due to stack frame creation, argument passing, and return value handling. The line profiler shows that the original
_shared_object_disabled()function was called 2,632 times, consuming 1.63ms total. By inlining this simplegetattrcall directly, we eliminate:The profiler results confirm this optimization: the conditional check time dropped from 7.55ms (76.7% of total time) to 1.69ms (39.2% of total time), achieving a 9% overall speedup.
Test Case Performance:
The annotated tests show consistent 6-13% improvements across various scenarios, with particularly strong gains in:
This optimization is especially valuable since
SharedObjectLoadingScopeis used in Keras model serialization/deserialization workflows, where it may be called frequently during model loading operations.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-SharedObjectLoadingScope.__enter__-mjado33jand push.