⚡️ Speed up method FigureManagers.get by 26%
          #476
        
          
      
  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.
  
    
  
    
📄 26% (0.26x) speedup for
FigureManagers.getinmarimo/_plugins/stateless/mpl/_mpl.py⏱️ Runtime :
228 microseconds→181 microseconds(best of392runs)📝 Explanation and details
The optimization replaces the
if key not in dictcheck with a try/except pattern, eliminating the double dictionary lookup that occurs in the original code.Key changes:
if figure_id not in self.figure_managers(lookup ⚡️ Speed up functionis_mangled_localby 19% #1) then accessesself.figure_managers[str(figure_id)](lookup ⚡️ Speed up functionis_mcp_config_emptyby 16% #2)self.figure_managers[figure_id](single lookup) and handles missing keys via exception handlingstr()conversion: The optimized code removesstr(figure_id)sincefigure_idis already typed asstrWhy this is faster:
In Python, dictionary lookups are relatively expensive operations. The original code performs two hash table lookups for every successful access, while the optimized version performs only one. Exception handling in Python is optimized for the common case where exceptions don't occur, making try/except faster than explicit membership testing when the key usually exists.
Performance characteristics:
The optimization is most effective for workloads where successful lookups are common and missing keys are exceptional cases.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-FigureManagers.get-mhb95izdand push.