⚡️ Speed up method CallbackRegistry._remove_proxy by 49%
#211
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.
📄 49% (0.49x) speedup for
CallbackRegistry._remove_proxyinlib/matplotlib/cbook.py⏱️ Runtime :
1.76 milliseconds→1.18 milliseconds(best of36runs)📝 Explanation and details
The optimization achieves a 49% speedup by eliminating redundant operations and reducing attribute lookups in the hot loop. Here are the key improvements:
1. Eliminated
list()conversion overhead:list(self._func_cid_map.items())creates an unnecessary copy of all itemsfunc_cid_map.items()saves memory allocation and copying2. Reduced attribute lookups:
self.callbacks[signal],self._func_cid_map,self._pickled_cidslookups in the loopcallbacks,func_cid_map,pickled_cids)3. Avoided wasteful
.pop()calls:proxy_to_cid.pop(proxy, None)on every iteration, even when proxy wasn't presentif proxy in proxy_to_cid:check first, then calledproxy_to_cid.pop(proxy)only when needed4. Simplified callback removal:
del self.callbacks[signal][cid]callbacks[signal].pop(cid, None)which is more defensiveThe line profiler shows the optimization's impact:
.pop()overhead reduced from 4.8ms to 4.4ms (8% improvement) due to fewer unnecessary callsPerformance characteristics:
.pop()callsThis optimization is particularly valuable since
_remove_proxyis called during cleanup operations when callbacks are disconnected or when weak references are garbage collected, making it performance-critical for applications with many dynamic callbacks.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-CallbackRegistry._remove_proxy-misaz0hrand push.