⚡️ Speed up method HardwareHandlerBase.get_wallet by 21%
#22
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.
📄 21% (0.21x) speedup for
HardwareHandlerBase.get_walletinelectrum/hw_wallet/plugin.py⏱️ Runtime :
387 microseconds→319 microseconds(best of182runs)📝 Explanation and details
The optimization achieves a 21% speedup through two key changes:
Local variable caching:
win = self.winstores the attribute in a local variable. Python's local variable lookup (LOAD_FAST) is faster than attribute access (LOAD_ATTR) because it uses array indexing instead of dictionary lookups.Single operation replacement: Replaces the two-step
hasattr(self.win, 'wallet')+self.win.walletpattern with a singlegetattr(win, 'wallet', None)call. This eliminates duplicate attribute lookups sincehasattrinternally performs the same attribute resolution as the subsequent access.The line profiler shows the optimization reduces both the number of attribute accesses (from 3 total
self.winlookups to 1) and overall execution time. The performance gains are most significant in scenarios with frequent method calls - test cases show 14-30% improvements when objects have thewalletattribute, and the large-scale tests demonstrate 23-24% speedups with repeated calls.The optimization is particularly effective for the common case where
winexists and has awalletattribute, as seen in the annotated tests where most positive cases show 12-30% improvements.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-HardwareHandlerBase.get_wallet-mhf87uhyand push.